Example #1
0
        /// <summary>
        /// Parses a header value into a value and a quality.
        /// </summary>
        /// <param name="headerValue"></param>
        /// <returns></returns>
        public static QualityValue Parse(string headerValue)
        {
            QualityValue result = null;

            if (headerValue != null)
            {
                var qValueIdx = headerValue.IndexOf(";q=", StringComparison.OrdinalIgnoreCase);

                double?quality = null;
                if (qValueIdx != -1 &&
                    double.TryParse(
                        headerValue.Substring(qValueIdx + 3),
                        NumberStyles.AllowDecimalPoint | NumberStyles.AllowTrailingWhite,
                        CultureInfo.InvariantCulture,
                        out var qualityParsed
                        ) &&
                    qualityParsed <= 1.0 &&
                    headerValue.Length - qValueIdx <= 8 &&      // Cannot exceed 3 decimal places
                    headerValue[qValueIdx + 3] != '.'           // Must start with a digit
                    )
                {
                    quality = qualityParsed;
                }
                else
                {
                    qValueIdx = -1;
                }

                var value = qValueIdx == -1 ? headerValue : headerValue.Substring(0, qValueIdx);

                result = new QualityValue(value, quality);
            }

            return(result);
        }
Example #2
0
        /// <summary>
        /// Parses a comma-separated list of q-value strings into a collection of <see cref="QualityValue"/>
        /// objects.
        /// </summary>
        /// <param name="headerValue"></param>
        /// <returns></returns>
        public static IList <QualityValue> ParseCommaSeparated(string headerValue)
        {
            var result = new List <QualityValue>();

            if (!String.IsNullOrWhiteSpace(headerValue))
            {
                foreach (var chunk in headerValue.Split(','))
                {
                    result.Add(QualityValue.Parse(chunk.Trim()));
                }
            }

            return(result);
        }