Пример #1
0
        /// <summary>
        /// Converts a string to a Duration value.
        /// </summary>
        /// <param name="text">String text to convert.</param>
        /// <param name="targetValue">After invocation, converted value.</param>
        /// <returns>true if the value was converted; false otherwise.</returns>
        /// <remarks>Copy of WebConvert.TryKeyStringToTime.</remarks>
        private static bool TryUriStringToDuration(string text, out TimeSpan targetValue)
        {
            if (!UriParserHelper.TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixDuration, ref text))
            {
                targetValue = default(TimeSpan);
                return(false);
            }

            if (!UriParserHelper.TryRemoveQuotes(ref text))
            {
                targetValue = default(TimeSpan);
                return(false);
            }

            try
            {
                targetValue = EdmValueParser.ParseDuration(text);
                return(true);
            }
            catch (FormatException)
            {
                targetValue = default(TimeSpan);
                return(false);
            }
        }
Пример #2
0
        /// <summary>
        /// Try to parse the given text to a Geometry object.
        /// </summary>
        /// <param name="text">Text to parse.</param>
        /// <param name="targetValue">Geometry to return.</param>
        /// <param name="parsingFailureReasonException">The detailed reason of parsing error.</param>
        /// <returns>True if succeeds, false if not.</returns>
        private static bool TryUriStringToGeometry(string text, out Geometry targetValue, out UriLiteralParsingException parsingFailureReasonException)
        {
            parsingFailureReasonException = null;

            if (!UriParserHelper.TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixGeometry, ref text))
            {
                targetValue = default(Geometry);
                return(false);
            }

            if (!UriParserHelper.TryRemoveQuotes(ref text))
            {
                targetValue = default(Geometry);
                return(false);
            }

            try
            {
                targetValue = LiteralUtils.ParseGeometry(text);
                return(true);
            }
            catch (ParseErrorException e)
            {
                targetValue = default(Geometry);

                parsingFailureReasonException =
                    new UriLiteralParsingException(e.Message);
                return(false);
            }
        }
Пример #3
0
        /// <summary>
        /// Converts a string to a byte[] value.
        /// </summary>
        /// <param name="text">String text to convert.</param>
        /// <param name="targetValue">After invocation, converted value.</param>
        /// <returns>true if the value was converted; false otherwise.</returns>
        /// <remarks>Copy of WebConvert.TryKeyStringToByteArray.</remarks>
        private static bool TryUriStringToByteArray(string text, out byte[] targetValue)
        {
            Debug.Assert(text != null, "text != null");

            if (!UriParserHelper.TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixBinary, ref text))
            {
                targetValue = null;
                return(false);
            }

            if (!UriParserHelper.TryRemoveQuotes(ref text))
            {
                targetValue = null;
                return(false);
            }

            try
            {
                targetValue = Convert.FromBase64String(text);
            }
            catch (FormatException)
            {
                targetValue = null;
                return(false);
            }

            return(true);
        }
Пример #4
0
            /// <summary>
            /// Tries to remove formatting specific to this parser's expected type.
            /// </summary>
            /// <param name="text">The text to remove formatting from.</param>
            /// <returns>Whether or not the expected formatting was found and succesfully removed.</returns>
            internal virtual bool TryRemoveFormatting(ref string text)
            {
                if (this.prefix != null)
                {
                    if (!UriParserHelper.TryRemovePrefix(this.prefix, ref text))
                    {
                        return(false);
                    }
                }

                bool shouldBeQuoted = this.prefix != null || ValueOfTypeCanContainQuotes(this.expectedType);

                if (shouldBeQuoted && !UriParserHelper.TryRemoveQuotes(ref text))
                {
                    return(false);
                }

                if (this.suffix != null)
                {
                    // we need to try to remove the literal even if it isn't required.
                    if (!TryRemoveLiteralSuffix(this.suffix, ref text) && this.suffixRequired)
                    {
                        return(false);
                    }
                }

                return(true);
            }
Пример #5
0
        internal static bool TryBindIdentifier(string identifier, IEdmEnumTypeReference typeReference, IEdmModel modelWhenNoTypeReference, out QueryNode boundEnum)
        {
            boundEnum = null;
            string text = identifier;

            // parse the string, e.g., NS.Color'Green'
            // get type information, and also convert Green into an ODataEnumValue

            // find the first ', before that, it is namespace.type
            int indexOfSingleQuote = text.IndexOf('\'');

            if (indexOfSingleQuote < 0)
            {
                return(false);
            }

            string namespaceAndType = text.Substring(0, indexOfSingleQuote);

            Debug.Assert((typeReference == null) || (modelWhenNoTypeReference == null), "((typeReference == null) || (modelWhenNoTypeReference == null)");

            // validate typeReference but allow type name not found in model for delayed throwing.
            if ((typeReference != null) && !string.Equals(namespaceAndType, typeReference.FullName()))
            {
                return(false);
            }

            // get the type
            IEdmEnumType enumType = typeReference != null
                ?
                                    (IEdmEnumType)typeReference.Definition
                :
                                    UriEdmHelpers.FindEnumTypeFromModel(modelWhenNoTypeReference, namespaceAndType);

            if (enumType == null)
            {
                return(false);
            }

            // now, find out the value
            UriParserHelper.TryRemovePrefix(namespaceAndType, ref text);
            UriParserHelper.TryRemoveQuotes(ref text);

            // parse string or int value to edm enum value
            string         enumValueString = text;
            ODataEnumValue enumValue;

            if (!TryParseEnum(enumType, enumValueString, out enumValue))
            {
                return(false);
            }

            // create an enum node, enclosing an odata enum value
            IEdmEnumTypeReference enumTypeReference = typeReference ?? new EdmEnumTypeReference(enumType, false);

            boundEnum = new ConstantNode(enumValue, identifier, enumTypeReference);

            return(true);
        }
Пример #6
0
        internal IEdmTypeReference GetLiteralEdmTypeReference()
        {
            Debug.Assert(this.Kind != ExpressionTokenKind.CustomTypeLiteral || this.LiteralEdmType != null, "ExpressionTokenKind is marked as CustomTypeLiteral but not EdmType was set");

            if (this.LiteralEdmType == null && this.Kind != ExpressionTokenKind.CustomTypeLiteral)
            {
                this.LiteralEdmType = UriParserHelper.GetLiteralEdmTypeReference(this.Kind);
            }

            return(this.LiteralEdmType);
        }
Пример #7
0
        /// <summary>
        /// Remove the given literal prefix
        /// </summary>
        /// <param name="literalPrefix">The custom name of the literal prefix</param>
        /// <returns>'true' if the literal prefix is successfully found and removed; otherwise, 'false'.</returns>
        /// <exception cref="ArgumentNullException">Argument is null or empty</exception>
        public static bool RemoveCustomLiteralPrefix(string literalPrefix)
        {
            // Arguments validation
            ExceptionUtils.CheckArgumentStringNotNullOrEmpty(literalPrefix, "literalPrefix");

            UriParserHelper.ValidatePrefixLiteral(literalPrefix);

            // Try to remove the custom uri literal prefix from cache
            lock (Locker)
            {
                return(CustomLiteralPrefixesOfEdmTypes.Remove(literalPrefix));
            }
        }
Пример #8
0
        public void TryRemoveQuotesTest()
        {
            string test = "' '";
            Assert.True(UriParserHelper.TryRemoveQuotes(ref test));
            Assert.Equal(test, " ");

            test = "invalid";
            Assert.False(UriParserHelper.TryRemoveQuotes(ref test));
            Assert.Equal(test, "invalid");

            test = "'invalid";
            Assert.False(UriParserHelper.TryRemoveQuotes(ref test));
            Assert.Equal(test, "'invalid");
        }
Пример #9
0
            /// <summary>
            /// Tries to remove formatting specific to this parser's expected type.
            /// </summary>
            /// <param name="text">The text to remove formatting from.</param>
            /// <returns>
            /// Whether or not the expected formatting was found and succesfully removed.
            /// </returns>
            internal override bool TryRemoveFormatting(ref string text)
            {
                if (!UriParserHelper.TryRemovePrefix(ExpressionConstants.LiteralPrefixBinary, ref text))
                {
                    return(false);
                }

                if (!UriParserHelper.TryRemoveQuotes(ref text))
                {
                    return(false);
                }

                return(true);
            }
Пример #10
0
        public void TryRemoveQuotesTest()
        {
            string test = "' '";

            UriParserHelper.TryRemoveQuotes(ref test).Should().BeTrue();
            test.Should().Be(" ");

            test = "invalid";
            UriParserHelper.TryRemoveQuotes(ref test).Should().BeFalse();
            test.Should().Be("invalid");

            test = "'invalid";
            UriParserHelper.TryRemoveQuotes(ref test).Should().BeFalse();
            test.Should().Be("'invalid");
        }
Пример #11
0
 public void IsCharHexDigitTest()
 {
     UriParserHelper.IsCharHexDigit(' ').Should().BeFalse();
     UriParserHelper.IsCharHexDigit('0').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('1').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('9').Should().BeTrue();
     UriParserHelper.IsCharHexDigit(':').Should().BeFalse();
     UriParserHelper.IsCharHexDigit('A').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('B').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('F').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('G').Should().BeFalse();
     UriParserHelper.IsCharHexDigit('a').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('b').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('f').Should().BeTrue();
     UriParserHelper.IsCharHexDigit('g').Should().BeFalse();
 }
Пример #12
0
 public void IsCharHexDigitTest()
 {
     Assert.False(UriParserHelper.IsCharHexDigit(' '));
     Assert.True(UriParserHelper.IsCharHexDigit('0'));
     Assert.True(UriParserHelper.IsCharHexDigit('1'));
     Assert.True(UriParserHelper.IsCharHexDigit('9'));
     Assert.False(UriParserHelper.IsCharHexDigit(':'));
     Assert.True(UriParserHelper.IsCharHexDigit('A'));
     Assert.True(UriParserHelper.IsCharHexDigit('B'));
     Assert.True(UriParserHelper.IsCharHexDigit('F'));
     Assert.False(UriParserHelper.IsCharHexDigit('G'));
     Assert.True(UriParserHelper.IsCharHexDigit('a'));
     Assert.True(UriParserHelper.IsCharHexDigit('b'));
     Assert.True(UriParserHelper.IsCharHexDigit('f'));
     Assert.False(UriParserHelper.IsCharHexDigit('g'));
 }
Пример #13
0
        /// <summary>
        /// Add a literal prefix for the given EdmType.
        /// </summary>
        /// <example>filter=MyProperty eq MyCustomLiteral'VALUE'.
        /// "MyCustomLiteral" is the literal prefix and the <paramref name="literalEdmTypeReference"/> is the type of the "VALUE".</example>
        /// <param name="literalPrefix">The custom name of the literal prefix</param>
        /// <param name="literalEdmTypeReference">The edm type of the custom literal</param>
        /// <exception cref="ArgumentNullException">Arguments are null or empty</exception>
        /// <exception cref="ArgumentException">The given literal prefix is not valid</exception>
        /// <exception cref="ODataException">The given literal prefix already exists</exception>
        public static void AddCustomLiteralPrefix(string literalPrefix, IEdmTypeReference literalEdmTypeReference)
        {
            // Arguments validation
            ExceptionUtils.CheckArgumentNotNull(literalEdmTypeReference, "literalEdmTypeReference");

            ExceptionUtils.CheckArgumentStringNotNullOrEmpty(literalPrefix, "literalPrefix");

            UriParserHelper.ValidatePrefixLiteral(literalPrefix);

            // Try to add the custom uri literal to cache
            lock (Locker)
            {
                // Check if literal does already exists
                if (CustomLiteralPrefixesOfEdmTypes.ContainsKey(literalPrefix))
                {
                    throw new ODataException(ODataErrorStrings.CustomUriTypePrefixLiterals_AddCustomUriTypePrefixLiteralAlreadyExists(literalPrefix));
                }

                CustomLiteralPrefixesOfEdmTypes.Add(literalPrefix, literalEdmTypeReference);
            }
        }
Пример #14
0
        /*variable*/


        /*private method*/
        private void Init()
        {
            UriParserHelper.RegisterRtspUri();
            InitEvent();
        }
Пример #15
0
 /// <summary>
 /// Tries to remove formatting specific to this parser's expected type.
 /// </summary>
 /// <param name="text">The text to remove formatting from.</param>
 /// <returns>
 /// Whether or not the expected formatting was found and succesfully removed.
 /// </returns>
 internal override bool TryRemoveFormatting(ref string text)
 {
     return(UriParserHelper.TryRemoveQuotes(ref text));
 }
Пример #16
0
        private bool TryUriStringToPrimitive(string text, IEdmTypeReference targetType, out object targetValue, out UriLiteralParsingException exception)
        {
            Debug.Assert(text != null, "text != null");
            Debug.Assert(targetType != null, "targetType != null");
            exception = null;

            try
            {
                if (targetType.IsNullable)
                {
                    // COMPAT 38: Product does not support "null" literals in service operation arguments
                    // check for the 'null' constant for nullable types
                    if (text == ExpressionConstants.KeywordNull)
                    {
                        targetValue = null;
                        return(true);
                    }
                }

                IEdmPrimitiveTypeReference primitiveTargetType = targetType.AsPrimitiveOrNull();
                if (primitiveTargetType == null)
                {
                    targetValue = null;
                    return(false);
                }

                EdmPrimitiveTypeKind targetTypeKind = primitiveTargetType.PrimitiveKind();

                byte[] byteArrayValue;
                bool   binaryResult = TryUriStringToByteArray(text, out byteArrayValue);
                if (targetTypeKind == EdmPrimitiveTypeKind.Binary)
                {
                    targetValue = (object)byteArrayValue;
                    return(binaryResult);
                }
                else if (binaryResult)
                {
                    string keyValue = Encoding.UTF8.GetString(byteArrayValue, 0, byteArrayValue.Length);
                    return(TryUriStringToPrimitive(keyValue, targetType, out targetValue));
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.Guid)
                {
                    Guid guidValue;
                    bool result = UriUtils.TryUriStringToGuid(text, out guidValue);
                    targetValue = guidValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.Date)
                {
                    Date dateValue;
                    bool result = UriUtils.TryUriStringToDate(text, out dateValue);
                    targetValue = dateValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.DateTimeOffset)
                {
                    DateTimeOffset dateTimeOffsetValue;
                    bool           result = UriUtils.ConvertUriStringToDateTimeOffset(text, out dateTimeOffsetValue);
                    targetValue = dateTimeOffsetValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.Duration)
                {
                    TimeSpan timespanValue;
                    bool     result = TryUriStringToDuration(text, out timespanValue);
                    targetValue = timespanValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.Geography)
                {
                    Geography geographyValue;
                    bool      result = TryUriStringToGeography(text, out geographyValue, out exception);
                    targetValue = geographyValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.Geometry)
                {
                    Geometry geometryValue;
                    bool     result = TryUriStringToGeometry(text, out geometryValue, out exception);
                    targetValue = geometryValue;
                    return(result);
                }
                else if (targetTypeKind == EdmPrimitiveTypeKind.TimeOfDay)
                {
                    TimeOfDay timeOfDayValue;
                    bool      result = UriUtils.TryUriStringToTimeOfDay(text, out timeOfDayValue);
                    targetValue = timeOfDayValue;
                    return(result);
                }

                bool quoted = targetTypeKind == EdmPrimitiveTypeKind.String;
                if (quoted != UriParserHelper.IsUriValueQuoted(text))
                {
                    targetValue = null;
                    return(false);
                }

                if (quoted)
                {
                    text = UriParserHelper.RemoveQuotes(text);
                }

                try
                {
                    switch (targetTypeKind)
                    {
                    case EdmPrimitiveTypeKind.String:
                        targetValue = text;
                        break;

                    case EdmPrimitiveTypeKind.Boolean:
                        targetValue = XmlConvert.ToBoolean(text);
                        break;

                    case EdmPrimitiveTypeKind.Byte:
                        targetValue = XmlConvert.ToByte(text);
                        break;

                    case EdmPrimitiveTypeKind.SByte:
                        targetValue = XmlConvert.ToSByte(text);
                        break;

                    case EdmPrimitiveTypeKind.Int16:
                        targetValue = XmlConvert.ToInt16(text);
                        break;

                    case EdmPrimitiveTypeKind.Int32:
                        targetValue = XmlConvert.ToInt32(text);
                        break;

                    case EdmPrimitiveTypeKind.Int64:
                        UriParserHelper.TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixInt64, ref text);
                        targetValue = XmlConvert.ToInt64(text);
                        break;

                    case EdmPrimitiveTypeKind.Single:
                        UriParserHelper.TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixSingle, ref text);
                        targetValue = XmlConvert.ToSingle(text);
                        break;

                    case EdmPrimitiveTypeKind.Double:
                        UriParserHelper.TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDouble, ref text);
                        targetValue = XmlConvert.ToDouble(text);
                        break;

                    case EdmPrimitiveTypeKind.Decimal:
                        UriParserHelper.TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDecimal, ref text);
                        try
                        {
                            targetValue = XmlConvert.ToDecimal(text);
                        }
                        catch (FormatException)
                        {
                            // we need to support exponential format for decimals since we used to support them in V1
                            decimal result;
                            if (Decimal.TryParse(text, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out result))
                            {
                                targetValue = result;
                            }
                            else
                            {
                                targetValue = default(Decimal);
                                return(false);
                            }
                        }

                        break;

                    default:
                        throw new ODataException(ODataErrorStrings.General_InternalError(InternalErrorCodes.UriPrimitiveTypeParser_TryUriStringToPrimitive));
                    }

                    return(true);
                }
                catch (FormatException)
                {
                    targetValue = null;
                    return(false);
                }
                catch (OverflowException)
                {
                    targetValue = null;
                    return(false);
                }
            }
            catch (Exception primitiveParserException)
            {
                exception = new UriLiteralParsingException(
                    string.Format(CultureInfo.InvariantCulture, ODataErrorStrings.UriPrimitiveTypeParsers_FailedToParseTextToPrimitiveValue(text, targetType),
                                  primitiveParserException));
                targetValue = null;
                return(false);
            }
        }
Пример #17
0
        /// <summary>Parses a token that starts with a digit.</summary>
        /// <returns>The kind of token recognized.</returns>
        private ExpressionTokenKind ParseFromDigit()
        {
            Debug.Assert(this.IsValidDigit || ('-' == this.ch), "this.IsValidDigit || ('-' == this.ch)");
            ExpressionTokenKind result;
            int  tokenPos  = this.textPos;
            char startChar = this.ch.Value;

            this.NextChar();
            if (startChar == '0' && (this.ch == 'x' || this.ch == 'X'))
            {
                result = ExpressionTokenKind.BinaryLiteral;
                do
                {
                    this.NextChar();
                }while (this.ch.HasValue && UriParserHelper.IsCharHexDigit(this.ch.Value));
            }
            else
            {
                result = ExpressionTokenKind.IntegerLiteral;
                while (this.IsValidDigit)
                {
                    this.NextChar();
                }

                // DateTimeOffset, Date and Guids will have '-' in them
                if (this.ch == '-')
                {
                    if (this.TryParseDateTimeoffset(tokenPos))
                    {
                        return(ExpressionTokenKind.DateTimeOffsetLiteral);
                    }
                    else if (this.TryParseGuid(tokenPos))
                    {
                        return(ExpressionTokenKind.GuidLiteral);
                    }
                }

                // TimeOfDay will have ":" in them
                if (this.ch == ':')
                {
                    if (this.TryParseTimeOfDay(tokenPos))
                    {
                        return(ExpressionTokenKind.TimeOfDayLiteral);
                    }
                }

                // Guids will have alpha-numeric characters along with '-', so if a letter is encountered
                // try to see if this is Guid or not.
                if (this.ch.HasValue && Char.IsLetter(this.ch.Value))
                {
                    if (this.TryParseGuid(tokenPos))
                    {
                        return(ExpressionTokenKind.GuidLiteral);
                    }
                }

                if (this.ch == '.')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                    this.ValidateDigit();

                    do
                    {
                        this.NextChar();
                    }while (this.IsValidDigit);
                }

                if (this.ch == 'E' || this.ch == 'e')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                    if (this.ch == '+' || this.ch == '-')
                    {
                        this.NextChar();
                    }

                    this.ValidateDigit();
                    do
                    {
                        this.NextChar();
                    }while (this.IsValidDigit);
                }

                if (this.ch == 'M' || this.ch == 'm')
                {
                    result = ExpressionTokenKind.DecimalLiteral;
                    this.NextChar();
                }
                else if (this.ch == 'd' || this.ch == 'D')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                }
                else if (this.ch == 'L' || this.ch == 'l')
                {
                    result = ExpressionTokenKind.Int64Literal;
                    this.NextChar();
                }
                else if (this.ch == 'f' || this.ch == 'F')
                {
                    result = ExpressionTokenKind.SingleLiteral;
                    this.NextChar();
                }
                else
                {
                    string valueStr = this.Text.Substring(tokenPos, this.textPos - tokenPos);
                    result = MakeBestGuessOnNoSuffixStr(valueStr, result);
                }
            }

            return(result);
        }