/// <summary>
        ///     Performs some basic validation on an IFormatProvider, including the existence of a default format and
        ///     supported formats.
        /// </summary>
        /// <param name="formatProvider">
        ///     The format provider to validate.
        /// </param>
        /// <exception cref="ArgumentException">
        ///     If the format provider cannot be validated, this exception is thrown with additional information.
        /// </exception>
        public static void Validate(this IFormatProvider formatProvider)
        {
            string defaultFormat = formatProvider.DefaultFormat();
            IEnumerable <SupportedFormat> supportedFormats = formatProvider.SupportedFormats();

            if (defaultFormat == null)
            {
                if (supportedFormats.Any())
                {
                    throw new ArgumentException("A format provider with supported formats must declare a default format");
                }

                return;
            }

            if (!supportedFormats.Any())
            {
                return;
            }

            string[] supportedFormatStrings = supportedFormats.Select(_ => _.Format).Distinct().ToArray();
            if (supportedFormats.Count() != supportedFormats.Count())
            {
                throw new ArgumentException("Duplicate supported format");
            }

            // todo: add a check that there's only one supported format that matches the default format

            if (!supportedFormatStrings.Any(_ => _ == defaultFormat))
            {
                throw new ArgumentException("Default format is unsupported");
            }

            var attributes = (SupportedFormatAttribute[])Attribute.GetCustomAttributes(formatProvider.GetType(), typeof(SupportedFormatAttribute));

            if (!attributes.OrderBy(_ => _.Ordinal).Select(_ => _.Ordinal)
                .SequenceEqual(Enumerable.Range(1, attributes.Length)))
            {
                throw new ArgumentException("Please fix the ordinals of the SupportedFormatAttributes");
            }
        }
Example #2
0
        public static SupportedFormat DefaultSupportedFormat(
            this IFormatProvider formatProvider)
        {
            if (formatProvider == null)
            {
                return(new SupportedFormat());
            }

            var formats = formatProvider.SupportedFormats();

            if (!formats.Any())
            {
                return(new SupportedFormat());
            }

            string defaultFormat = formatProvider.DefaultFormat();

            if (defaultFormat == null)
            {
                return(new SupportedFormat());
            }

            return(formats.Single(x => x.Format == defaultFormat));
        }