Exemple #1
0
        public string ToString(string format, IFormatProvider formatProvider = null)
        {
            //Supported formats: C - compact, F - full, I - only id, J - json
            if (format == null)
            {
                format = "G";
            }
            format = format.ToLower();

            if (formatProvider?.GetFormat(GetType()) is ICustomFormatter formatter)
            {
                return(formatter.Format(format, this, formatProvider));
            }

            switch (format)
            {
            case "c":
                return($"{Id}-{Name}");

            case "f":
                return($"{Id}({Name}):[IsUp={!IsProducerDown},Timestamp={LastTimestampBeforeDisconnect:dd.MM.yyyy-HH:mm:ss.fff}]");

            case "i":
                return(Id.ToString());

            //case "g":
            default:
                return($"{Id}({Name}):[IsUp={!IsProducerDown},Timestamp={LastTimestampBeforeDisconnect:dd.MM.yyyy-HH:mm:ss.fff}]");
            }
        }
Exemple #2
0
 /// <summary>
 /// 将字节流转换为指定对象
 /// </summary>
 /// <param name="bytes"> </param>
 /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
 /// <returns> </returns>
 public virtual T Deserialize <T>(byte[] bytes, IFormatProvider formatProvider)
 {
     try
     {
         var instance = Activator.CreateInstance <T>();
         var props    = PropertyHandlerCollection.Get(typeof(T));
         var kv       = Deserialize(bytes, formatProvider);
         if (kv == null)
         {
             throw new NotSupportedException("无法转为实体");
         }
         foreach (var o in kv)
         {
             props[o.Key]?.SetValue(instance, o.Value);
         }
         return(instance);
     }
     catch (Exception ex)
     {
         if (bytes?.Length > 0)
         {
             var charset = formatProvider?.GetFormat(typeof(Encoding)) as Encoding;
             if (charset == null)
             {
                 ex.Data["ResponseBody"] = ex.Source = "base64:" + Convert.ToBase64String(bytes);
             }
             else
             {
                 ex.Data["ResponseBody"] = ex.Source = charset.GetString(bytes);
             }
         }
         throw;
     }
 }
Exemple #3
0
		public string ToString(string format, IFormatProvider formatProvider) {
			if (formatProvider != null) {
				ICustomFormatter fmt = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;
				if (fmt != null)
					return fmt.Format(format, this, formatProvider);
			}

			switch (format) {
				case "g": {
						string s = Group.ToString("x4");
						string x = String.Empty;
						x += ((Mask & 0xf0000000) != 0) ? s[0] : 'x';
						x += ((Mask & 0x0f000000) != 0) ? s[1] : 'x';
						x += ((Mask & 0x00f00000) != 0) ? s[2] : 'x';
						x += ((Mask & 0x000f0000) != 0) ? s[3] : 'x';
						return x;
					}
				case "e": {
						string s = Element.ToString("x4");
						string x = String.Empty;
						x += ((Mask & 0x0000f000) != 0) ? s[0] : 'x';
						x += ((Mask & 0x00000f00) != 0) ? s[1] : 'x';
						x += ((Mask & 0x000000f0) != 0) ? s[2] : 'x';
						x += ((Mask & 0x0000000f) != 0) ? s[3] : 'x';
						return x;
					}
				case "G":
				default: {
						return String.Format("({0},{1})", this.ToString("g", null), this.ToString("e", null));
					}
			}
		}
Exemple #4
0
        public static bool TryParse(string value, IFormatProvider formatProvider, out Money result)
        {
            if (value == null)
            {
                result = default;
                return(false);
            }

            NumberFormatInfo numberFormat =
                (NumberFormatInfo)formatProvider?.GetFormat(typeof(NumberFormatInfo)) ??
                NumberFormatInfo.CurrentInfo;

            var currencyString = ExtractCurrencyString(value, numberFormat);

            if (!Currency.TryParse(currencyString, out Currency currency))
            {
                currency = Currency.None;
            }

            numberFormat = (NumberFormatInfo)numberFormat.Clone();
            numberFormat.CurrencySymbol = currency != Currency.None ? currencyString : "¤";

            if (decimal.TryParse(value, NumberStyles.Currency, numberFormat, out decimal amount))
            {
                result = new Money(amount, currency);
                return(true);
            }
            else
            {
                result = default;
                return(false);
            }
        }
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (formatProvider == null)
            {
                return this.ToString();
            }

            ICustomFormatter fmt = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;

            if (fmt != null)
            {
                return fmt.Format(format, this, formatProvider);
            }

            switch (format)
            {
                case "V":
                    return this.Value;
                case "O":
                    return this.Operator.ToString();
                case "G":
                default:
                    return this.ToString();
            }
        }
        public DateTime ConvertFrom(RedisValue value, IFormatProvider provider)
        {
            var dateOnly = false;
            var kind     = DateTimeKind.Local;

            var formatInfo = provider?.GetFormat(typeof(DateTimeConvertionInfo)) as DateTimeConvertionInfo;

            if (formatInfo != null)
            {
                kind     = formatInfo.Kind;
                dateOnly = formatInfo.DateOnly;
            }

            var dateTime = DateTime.SpecifyKind(
                DateTime.ParseExact((string)value, dateOnly ? DateOnlyFormat : DateTimeFormat, CultureInfo.InvariantCulture),
                dateOnly ? DateTimeKind.Unspecified : DateTimeKind.Utc);

            if (dateOnly == false && kind == DateTimeKind.Local)
            {
                return(dateTime.ToLocalTime());
            }
            else
            {
                return(dateTime);
            }
        }
Exemple #7
0
        /// <summary>Formats the value of the current instance using the specified format.</summary>
        /// <returns>The value of the current instance in the specified format.</returns>
        /// <param name="format">
        ///     The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format
        ///     defined for the type of the <see cref="T:System.IFormattable" /> implementation.
        /// </param>
        /// <param name="formatProvider">
        ///     The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to
        ///     obtain the numeric format information from the current locale setting of the operating system.
        /// </param>
        public string ToString(string format, IFormatProvider formatProvider = null)
        {
            //Supported formats: C - compact, F - full, I - only id, J - json
            if (format == null)
            {
                format = "G";
            }
            format = format.ToLower();

            var formatter = formatProvider?.GetFormat(GetType()) as ICustomFormatter;

            if (formatter != null)
            {
                return(formatter.Format(format, this, formatProvider));
            }

            switch (format)
            {
            case "c":
                return(PrintC());

            case "f":
                return(PrintF());

            case "j":
                return(PrintJ());

            //case "i":
            //case "g":
            default:
                return(PrintI());
            }
        }
        private TimeTextInfo GetTimeTextInfo(IFormatProvider provider)
        {
            if (provider != null)
            {
                // See if the provider can give us what we want:
                var timeTextInfo = (TimeTextInfo)provider.GetFormat(typeof (TimeTextInfo));
                if (timeTextInfo != null)
                {
                    return timeTextInfo;
                }

                // See if there is a rule for this culture:
                var cultureInfo = provider as CultureInfo;
                if (cultureInfo != null)
                {
                    timeTextInfo = CommonLanguagesTimeTextInfo.GetTimeTextInfo(cultureInfo.TwoLetterISOLanguageName);
                    // If cultureInfo was supplied, 
                    // we will always return, even if null:
                    return timeTextInfo;
                }
            }

            // Return the default if the provider couldn't provide:
            return CommonLanguagesTimeTextInfo.GetTimeTextInfo(defaultTwoLetterISOLanguageName);
        }
Exemple #9
0
    /// <summary>
    /// Default formats:
    /// <para>t - SemVer 2.0 formatted tag [beta.1]</para>
    /// <para>l - Legacy SemVer tag with the tag number padded. [beta1]</para>
    /// <para>lp - Legacy SemVer tag with the tag number padded. [beta0001]. Can specify an integer to control padding (i.e., lp5)</para>
    /// </summary>
    public string ToString(string?format, IFormatProvider?formatProvider)
    {
        if (formatProvider?.GetFormat(GetType()) is ICustomFormatter formatter)
        {
            return(formatter.Format(format, this, formatProvider));
        }

        if (format.IsNullOrEmpty())
        {
            format = "t";
        }

        format = format.ToLower();
        if (format.StartsWith("lp", StringComparison.Ordinal))
        {
            // Handle format
            var padding = 4;
            if (format.Length > 2)
            {
                // try to parse
                if (int.TryParse(format.Substring(2), out var p))
                {
                    padding = p;
                }
            }

            return(Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString("D" + padding)) : FormatLegacy(GetLegacyName()));
        }

        return(format switch
        {
            "t" => (Number.HasValue ? Name.IsNullOrEmpty() ? $"{Number}" : $"{Name}.{Number}" : Name ?? string.Empty),
            "l" => (Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName())),
            _ => throw new FormatException($"Unknown format '{format}'.")
        });
Exemple #10
0
 /// <summary>Initializes the builder.</summary>
 /// <param name="scratchBuffer">A buffer temporarily transferred to the builder for use as part of its formatting.  Contents may be overwritten.</param>
 /// <param name="provider">An object that supplies culture-specific formatting information.</param>
 private InterpolatedStringBuilder(Span <char> scratchBuffer, IFormatProvider?provider)
 {
     _provider            = provider;
     _customFormatter     = provider?.GetFormat(typeof(ICustomFormatter));
     _arrayToReturnToPool = null;
     _chars = scratchBuffer;
     _pos   = 0;
 }
Exemple #11
0
        public string ToString(string format, IFormatProvider formatProvider)
        {
            NumberFormatInfo numberFormat =
                (NumberFormatInfo)formatProvider?.GetFormat(typeof(NumberFormatInfo)) ??
                NumberFormatInfo.CurrentInfo;

            return(_amount.ToString(format, CustomizeNumberFormat(numberFormat)));
        }
Exemple #12
0
        /// <summary>Initializes the builder.</summary>
        /// <param name="initialCapacity">Approximated capacity required to support the interpolated string.  The final size may be smaller or larger.</param>
        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
        private InterpolatedStringBuilder(int initialCapacity, IFormatProvider?provider)
        {
            _provider        = provider;
            _customFormatter = provider?.GetFormat(typeof(ICustomFormatter));
            _chars           = _arrayToReturnToPool = ArrayPool <char> .Shared.Rent(initialCapacity);

            _pos = 0;
        }
        /// <summary>
        /// Formats the value of the current instance using the specified format. The numbers are however culture invariant.
        /// </summary>
        /// <returns>
        /// The value of the current instance in the specified format.
        /// </returns>
        /// <param name="format">The format to use.
        /// <list type="table">
        /// <listheader><term>symbol</term><description>description</description></listheader>
        /// <item><term>G</term><description>General format: numerator/denominator</description></item>
        /// <item><term>n</term><description>Numerator</description></item>
        /// <item><term>d</term><description>Denominator</description></item>
        /// <item><term>z</term><description>The fraction as integer</description></item>
        /// <item><term>r</term><description>The positive remainder of all digits after the decimal point using the format: numerator/denominator or <see cref="string.Empty"/> if the fraction is a valid integer without digits after the decimal point.</description></item>
        /// <item><term>m</term><description>The fraction as mixed number e.g. "2 1/3" instead of "7/3"</description></item>
        /// </list>
        /// -or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation. </param>
        /// <param name="formatProvider">The provider to use to format the value. -or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
        /// <filterpriority>2</filterpriority>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            var formatter = formatProvider?.GetFormat(GetType()) as ICustomFormatter;

            return(formatter != null
                ? formatter.Format(format, this, formatProvider)
                : DefaultFractionFormatter.Instance.Format(format, this, formatProvider));
        }
Exemple #14
0
        private string Pluralize(string name, IFormatProvider formatProvider)
        {
            var pluralizer =
                formatProvider?.GetFormat <IPluralizer>()
                ?? _standardPluralizer;

            return(pluralizer.Pluralize(name));
        }
Exemple #15
0
    private void AppendCustomFormatter <T>(T value, string?format)
    {
        ICustomFormatter?formatter = (ICustomFormatter?)formatProvider?.GetFormat(typeof(ICustomFormatter));

        if (formatter is not null && formatter.Format(format, value, formatProvider) is string customFormatted)
        {
            AppendStringDirect(customFormatted);
        }
    }
Exemple #16
0
        /// <summary>
        /// Returns a string representation of this file size, using the provided format modifier
        /// and provider.
        /// </summary>
        /// <remarks>
        /// The format modifier either specifies only a unit size (e.g. 'B', 'KB', 'MB', or the special 'FS') or
        /// a number formatter plus unit size, separated by a colon (e.g. 'N2:GB' for a gigabyte representation
        /// to 2 decimal places).
        /// </remarks>
        /// <param name="format">The format to use.</param>
        /// <param name="formatProvider">A format provider which may contain a custom formatter to use instead
        /// of the default provided by this method.</param>
        /// <returns>A string representation of this file size.</returns>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (formatProvider?.GetFormat(typeof(FileSize)) is ICustomFormatter formatter)
            {
                return(formatter.Format(format, this, formatProvider));
            }

            return(GetUnitSizeForFormat(format, this.Bytes).Format(this.Bytes));
        }
Exemple #17
0
 /// <summary>
 /// An alternative for the ToString() method of DateTime to work around a problem with implementing custom formatters for DateTime objects
 /// The default implementation, even if given a good IFormatProvider implementation, would never call a custom formatter. It would
 /// still use the default formatter.
 /// </summary>
 /// <param name="dateTime">The date time object.</param>
 /// <param name="provider">The provider.</param>
 /// <param name="format">The format.</param>
 /// <returns></returns>
 public static string ToStringExtended(this DateTime dateTime, string format, IFormatProvider provider)
 {
     var formatter = provider.GetFormat(typeof(DateTimeFormatInfo)) as ICustomFormatter;
     if (formatter != null)
     {
         return formatter.Format(format, dateTime, provider);
     }
     throw new ArgumentException("The format provider argument did not return an instance that implements ICustomFormatter", "provider");
 }
Exemple #18
0
 /// <summary>
 /// 将字节流转换为键值对枚举
 /// </summary>
 /// <param name="bytes"> </param>
 /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
 /// <returns> </returns>
 public override IEnumerable <KeyValuePair <string, object> > Deserialize(byte[] bytes, IFormatProvider formatProvider)
 {
     if (bytes?.Length > 0)
     {
         var charset = formatProvider?.GetFormat(typeof(Encoding)) as Encoding ?? Encoding.Default;
         var text    = charset.GetString(bytes);
         yield return(new KeyValuePair <string, object>(null, text));
     }
 }
Exemple #19
0
        /// <summary>
        /// Gets a string representation of the current instance, using the specified format provider,
        /// which should be able to return an instance of <see cref="IFormatsFraction"/>.
        /// </summary>
        /// <returns>The string representation.</returns>
        /// <param name="format">The format specifier.</param>
        /// <param name="formatProvider">A format provider, which should be able to return an <see cref="IFormatsFraction"/>.</param>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            var formatter = formatProvider?.GetFormat(typeof(IFormatsFraction)) as IFormatsFraction;

            if (formatter == null)
            {
                return(ToString());
            }
            return(formatter.Format(this, format));
        }
Exemple #20
0
 public object GetFormat(Type formatType)
 {
     if (_provider != null)
     {
     }
     else
     {
     }
     return(_provider?.GetFormat(formatType));
 }
		public static DateTimeFormatInfo GetInstance(IFormatProvider fp) {
			if (fp != null) {
				DateTimeFormatInfo dtf = (DateTimeFormatInfo)fp.GetFormat(typeof(DateTimeFormatInfo));
				if (dtf != null) {
					return dtf;
				}
			}

			return CurrentInfo;
		}
Exemple #22
0
    private bool AppendCustomFormatter <T>(T value, string?format)
    {
        ICustomFormatter?formatter = (ICustomFormatter?)formatProvider?.GetFormat(typeof(ICustomFormatter));

        if (formatter is not null && formatter.Format(format, value, formatProvider) is string customFormatted)
        {
            return(AppendStringDirect(customFormatted));
        }

        return(true);
    }
 /// <summary>
 ///  指定された型の書式設定サービスを取得します。
 /// </summary>
 /// <param name="formatType">書式設定サービスの種類です。</param>
 /// <returns>書式設定サービスを表すオブジェクトです。</returns>
 public virtual object?GetFormat(Type?formatType)
 {
     if (formatType?.IsAssignableFrom(this.GetType()) ?? false)
     {
         return(this);
     }
     else
     {
         return(_provider?.GetFormat(formatType));
     }
 }
Exemple #24
0
        /// <summary>
        /// Convert Enum to RedisValue
        /// </summary>
        /// <param name="value">enum value to convert</param>
        /// <param name="type">enum type to convert</param>
        /// <param name="provider">provider controls how enum value is converted</param>
        /// <returns>RedisValue represents enum value</returns>
        public static RedisValue ConvertTo(object value, Type type, IFormatProvider provider)
        {
            var format     = "g";
            var formatInfo = provider?.GetFormat(typeof(EnumConvertionInfo)) as EnumConvertionInfo;

            if (formatInfo != null && formatInfo.Convertion == EnumConvertion.AsNumeric)
            {
                format = "d";
            }

            return(Enum.Format(type, value, format));
        }
        /// <summary>
        /// <para>s - Default SemVer [1.2.3-beta.4+5]</para>
        /// <para>f - Full SemVer [1.2.3-beta.4+5]</para>
        /// <para>i - Informational SemVer [1.2.3-beta.4+5.Branch.main.BranchType.main.Sha.000000]</para>
        /// <para>j - Just the SemVer part [1.2.3]</para>
        /// <para>t - SemVer with the tag [1.2.3-beta.4]</para>
        /// <para>l - Legacy SemVer tag for systems which do not support SemVer 2.0 properly [1.2.3-beta4]</para>
        /// <para>lp - Legacy SemVer tag for systems which do not support SemVer 2.0 properly (padded) [1.2.3-beta0004]</para>
        /// </summary>
        public string ToString(string format, IFormatProvider formatProvider = null)
        {
            if (string.IsNullOrEmpty(format))
            {
                format = "s";
            }

            if (formatProvider?.GetFormat(GetType()) is ICustomFormatter formatter)
            {
                return(formatter.Format(format, this, formatProvider));
            }

            // Check for lp first because the param can vary
            format = format.ToLower();
            if (format.StartsWith("lp", StringComparison.Ordinal))
            {
                // handle the padding
                return(PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString(format)}" : ToString("j"));
            }

            switch (format)
            {
            case "j":
                return($"{Major}.{Minor}.{Patch}");

            case "s":
                return(PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag}" : ToString("j"));

            case "t":
                return(PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("t")}" : ToString("j"));

            case "l":
                return(PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("l")}" : ToString("j"));

            case "f":
            {
                var buildMetadata = BuildMetaData.ToString();

                return(!string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"));
            }

            case "i":
            {
                var buildMetadata = BuildMetaData.ToString("f");

                return(!string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"));
            }

            default:
                throw new ArgumentException($"Unrecognised format '{format}'", nameof(format));
            }
        }
        /// <summary>
        /// Represents a customer in the specified format and culture
        /// </summary>
        /// <param name="format">Format string</param>
        /// <param name="provider">Format provider</param>
        /// <returns>Formatted string</returns>
        public string ToString(string format, IFormatProvider provider)
        {
            string currentFormat = string.IsNullOrEmpty(format) ? GeneralFormatStr : format;

            ICustomFormatter formatter = provider?.GetFormat(GetType()) as ICustomFormatter;

            if (formatter != null)
            {
                return(formatter.Format(currentFormat, this, provider));
            }

            return(GetFormattedString(currentFormat, provider));
        }
        public decimal Parse(IFormatProvider provider, decimal defaultValue = default(decimal), bool round = false)
        {
            var result = _converter.Parse(provider, defaultValue);

            if (round)
            {
                provider = provider ?? CultureInfo.CurrentCulture;
                var numberFormat = (NumberFormatInfo)provider.GetFormat(typeof(NumberFormatInfo)) ?? CultureInfo.CurrentCulture.NumberFormat;
                return Math.Round(result, numberFormat.CurrencyDecimalDigits);
            }

            return result;
        }
Exemple #28
0
        private static bool UnsignedFormat(this ulong value, Span <char> target, out int charsWritten, IFormatProvider provider = null)
        {
            charsWritten = 0;

            var info = provider?.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo ?? NumberFormatInfo.CurrentInfo;

            if (value == 0)
            {
                if (info.NativeDigits[0].AsSpan().TryCopyTo(target))
                {
                    charsWritten = info.NativeDigits[0].Length;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            var ind = 0;

            var n = value.SignificantDigitsCount();

            Span <char> buff = stackalloc char[4 * n];

            while (value != 0)
            {
                var rem   = value % 10u;
                var digit = info.NativeDigits[rem].AsSpan();

                digit.CopyTo(buff.Slice(ind));

                ind += digit.Length;

                value /= 10u;
            }

            if (ind >= target.Length)
            {
                return(false);
            }

            for (var i = 0; i < ind; i++)
            {
                target[i] = buff[ind - i - 1];
            }

            charsWritten = ind;

            return(true);
        }
Exemple #29
0
        public void Parse(out BigRational result, string s, IFormatProvider provider)
        {
            NumberFormatInfo numberFormatProvider = (NumberFormatInfo)provider?.GetFormat(typeof(NumberFormatInfo));

            if (numberFormatProvider == null)
            {
                numberFormatProvider = CultureInfo.CurrentCulture.NumberFormat;
            }

            int pos = s.IndexOf(numberFormatProvider.NumberDecimalSeparator);

            if (pos < 0)
            {
                var value = BigInteger.Parse(s, provider);
                result = new BigRational(value);
            }
            else
            {
                var strWholePart = s.Substring(0, pos).TrimStart();
                var strFractPart = pos < s.Length ? s.Substring(pos + 1) : string.Empty;

                BigInteger bigWholePart = BigInteger.Zero;
                if (!string.IsNullOrEmpty(strWholePart) && strWholePart != "-")
                {
                    bigWholePart = BigInteger.Parse(strWholePart, provider);
                }

                BigInteger bigFractPart = BigInteger.Zero;
                if (!string.IsNullOrEmpty(strFractPart))
                {
                    var pow = new BigRational((long)Math.Pow(10, strFractPart.Length));
                    bigFractPart = BigInteger.Parse(strFractPart, provider);

                    if (bigWholePart.Sign < 0 || (bigWholePart.IsZero && strWholePart.StartsWith(numberFormatProvider.NegativeSign)))
                    {
                        bigFractPart = BigInteger.Negate(bigFractPart);
                    }

                    var rationalWhole = new BigRational(bigWholePart);
                    var rationalFract = new BigRational(bigFractPart);

                    rationalFract.Divide(out rationalFract, ref pow);
                    rationalWhole.Add(out result, ref rationalFract);
                }
                else
                {
                    result = new BigRational(bigWholePart);
                }
            }
        }
 public static bool HasFormatted(
     this IFormatProvider? @this, object obj, string?format, [NotNullWhen(true)] out string?result)
 {
     if (@this?.GetFormat(obj.GetType()) is ICustomFormatter customFormatter)
     {
         result = customFormatter.Format(format, obj, @this);
         return(true);
     }
     else
     {
         result = null;
         return(false);
     }
 }
Exemple #31
0
 internal static CultureInfo?FormatProviderToCultureInfo(IFormatProvider?formatProvider)
 {
     if (formatProvider is CultureInfo ci)
     {
         return(ci);
     }
     else if (formatProvider?.GetFormat(typeof(CultureInfo)) is CultureInfo ci2)
     {
         return(ci2);
     }
     else
     {
         return(CultureInfo.CurrentCulture);
     }
 }
        public decimal? Parse(IFormatProvider provider, bool round = false)
        {
            var result = _converter.Parse(provider);
            if (!result.HasValue)
                return null;

            if (round)
            {
                provider = provider ?? CultureInfo.CurrentCulture;
                var numberFormat = (NumberFormatInfo)provider.GetFormat(typeof(NumberFormatInfo)) ?? CultureInfo.CurrentCulture.NumberFormat;
                return Math.Round(result.Value, numberFormat.CurrencyDecimalDigits);
            }

            return result;
        }
        /// <summary>
        /// Sets a DateTime formatter to be used for outputting the DateTime values
        /// </summary>
        /// <param name="formatProvider">Format provider</param>
        /// <returns>A Collapse instance, used for chaining</returns>
        public Collapse SetDateTimeFormat(IFormatProvider formatProvider)
        {
            if(formatProvider == null)
                throw new ArgumentNullException("formatProvider", "Format provider was not supplied.");

            DateTimeFormatInfo formatInfo =
                formatProvider.GetFormat(typeof(DateTimeFormatInfo)) as DateTimeFormatInfo;

            if (formatInfo == null)
                throw new DateTimeFormatInvalidException();

            SetDateTimeFormat(
                String.Format("{0} {1}", formatInfo.ShortDatePattern, formatInfo.LongTimePattern));

            return this;
        }
Exemple #34
0
        private bool TryFormatter(string format, IFormatProvider formatProvider, out string formattedString)
        {
            var formatted = false;

            formattedString = null;

            var formatter = formatProvider?.GetFormat(typeof(Version)) as ICustomFormatter;

            if (formatter != null)
            {
                formatted       = true;
                formattedString = formatter.Format(format, this, formatProvider);
            }

            return(formatted);
        }
Exemple #35
0
        public override byte[] Serialize(string format, IEnumerable <KeyValuePair <string, object> > body, IFormatProvider formatProvider)
        {
            var data  = body.FirstOrDefault(it => it.Key == null).Value;
            var bytes = data as byte[];

            if (bytes != null)
            {
                return(bytes);
            }
            var charset = formatProvider?.GetFormat(typeof(Encoding)) as Encoding ?? Encoding.Default;
            var str     = data as string;

            if (str != null)
            {
                return(charset.GetBytes(str));
            }
            throw new NotSupportedException("不支持");
        }
        public RedisValue ConvertTo(DateTime value, IFormatProvider provider)
        {
            var dateOnly = false;

            var formatInfo = provider?.GetFormat(typeof(DateTimeConvertionInfo)) as DateTimeConvertionInfo;

            if (formatInfo != null)
            {
                dateOnly = formatInfo.DateOnly;
            }

            if (dateOnly)
            {
                return(value.ToString(DateOnlyFormat));
            }
            else
            {
                return(value.ToUniversalTime().ToString(DateTimeFormat));
            }
        }
Exemple #37
0
        /// <summary>
        /// 将正文内容(<paramref name="arg" />)按照<paramref name="formatProvider" />中的编码信息转为等效的字符串
        /// </summary>
        /// <exception cref="FormatException"> <paramref name="arg" />必须是 IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt;. </exception>
        public virtual string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (arg == null)
            {
                return(null);
            }
            var body = arg as IEnumerable <KeyValuePair <string, object> >;

            if (body == null)
            {
                throw new FormatException(nameof(arg) + "必须是" + nameof(IEnumerable <KeyValuePair <string, object> >));
            }
            var bytes = Serialize(format, body, formatProvider);

            if (bytes?.Length > 0)
            {
                var charset = formatProvider?.GetFormat(typeof(Encoding)) as Encoding ?? Encoding.Default;
                return(charset.GetString(bytes));
            }
            return(null);
        }
		NumberFormatInfo(IFormatProvider provider)
	{
		if(provider == null)
		{
			return System.Globalization.NumberFormatInfo.CurrentInfo;
		}
		else
		{
			NumberFormatInfo nfi =
				(NumberFormatInfo) provider.GetFormat(
								typeof(System.Globalization.NumberFormatInfo));
			if(nfi != null)
			{
				return nfi;
			}
			else
			{
				return System.Globalization.NumberFormatInfo.CurrentInfo;
			}
		}
	}
    public int ToInt32(IFormatProvider provider)
    {
        bool toMinValue = true;

        if (provider != null)
        {
            TestFormatProvider format = provider.GetFormat(typeof(TestFormatProvider)) as TestFormatProvider;
            if ((format != null) && format.ToInt16MaxValue)
            {
                toMinValue = false;
            }
        }

        if (toMinValue)
        {
            return Int32.MinValue;
        }
        else
        {
            return Int32.MaxValue;
        }
    }
Exemple #40
0
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (formatProvider != null)
            {
                ICustomFormatter fmt = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;
                if (fmt != null)
                {
                    return fmt.Format(format, this, formatProvider);
                }
            }

            switch (format)
            {
                case "n":
                    return Name;
                case "p":
                    return PhoneNumber;
                case "a":
                    return Name + PhoneNumber;
                default:
                    return Name;
            }
        }
Exemple #41
0
        /// <summary>
        /// This method returns a string representation of the DicomTag.
        /// Use one of the following formats as parameter:
        /// - "G": returns for example "(0028,0010)" for public and "(0029,1001:MYPRIVATE)" for private tags
        /// - "X": returns for example "(0028,0010)" for public and "(0029,xx01:MYPRIVATE)" for private tags
        /// - "J": returns for example "00280010" for public and "00291001" for private tags
        /// </summary>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (formatProvider?.GetFormat(GetType()) is ICustomFormatter fmt)
            {
                return(fmt.Format(format, this, formatProvider));
            }

            switch (format)
            {
            case "X":
            {
                return((PrivateCreator != null)
                            ? string.Format("({0:x4},xx{1:x2}:{2})", Group, Element & 0xff, PrivateCreator.Creator)
                            : string.Format("({0:x4},{1:x4})", Group, Element));
            }

            case "g":
            {
                return((PrivateCreator != null)
                            ? string.Format("{0:x4},{1:x4}:{2}", Group, Element, PrivateCreator.Creator)
                            : string.Format("{0:x4},{1:x4}", Group, Element));
            }

            case "J":
            {
                return(string.Format("{0:X4}{1:X4}", Group, Element));
            }

            case "G":
            default:
            {
                return((PrivateCreator != null)
                            ? string.Format("({0:x4},{1:x4}:{2})", Group, Element, PrivateCreator.Creator)
                            : string.Format("({0:x4},{1:x4})", Group, Element));
            }
            }
        }
        public static string ToJavaFormatString(string format, IFormatProvider provider, DateTimeKind kind, bool dateTimeOffset, out bool useInvariant, out bool foundDateTimeKind, out bool useUtc)
        {
            if (string.IsNullOrEmpty(format))
                format = "G";

            DateTimeFormatInfo dtfi = null;

            if (provider != null)
                dtfi = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));

            if (dtfi == null)
                dtfi = DateTimeFormatInfo.CurrentInfo;

            bool needsTranslation = true;

            if (format.Length == 1 && dtfi != null)
            {
                format = GetStandardPattern(format[0], dtfi, dateTimeOffset, out useUtc, out useInvariant, out needsTranslation);

                if (format == null)
                    throw new FormatException(
                        "format is not one of the format specifier characters defined for DateTimeFormatInfo");
            }
            else
            {
                useInvariant = false;
                useUtc = false;
            }

            if (needsTranslation)
                format = ConvertFormatStringNetToJava(format, kind, out foundDateTimeKind);
            else
                foundDateTimeKind = false;

            return format;
        }
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (formatProvider != null)
            {
                ICustomFormatter fmt = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;
                if (fmt != null) { return fmt.Format(format, this, formatProvider); }
            }

            Question question = null;
            if (arg is Question)
            {
                question = arg as Question;
            }
            else
            {
                var questions = arg as Question[];
                question = questions.First(e => e.Key == format);
            }

            if (question.Value != null)
                return question.Value.ToString();

            return string.Format(format, "{0}", arg);
        }
        public StringBuilder AppendFormat(IFormatProvider provider, String format, params Object[] args) {
            if (format == null || args == null) {
                throw new ArgumentNullException((format == null) ? "format" : "args");
            }
            Contract.Ensures(Contract.Result<StringBuilder>() != null);
            Contract.EndContractBlock();

            int pos = 0;
            int len = format.Length;
            char ch = '\x0';

            ICustomFormatter cf = null;
            if (provider != null) {
                cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
            }

            while (true) {
                int p = pos;
                int i = pos;
                while (pos < len) {
                    ch = format[pos];

                    pos++;
                    if (ch == '}')
                    {
                        if (pos < len && format[pos] == '}') // Treat as escape character for }}
                            pos++;
                        else
                            FormatError();
                    }

                    if (ch == '{')
                    {
                        if (pos < len && format[pos] == '{') // Treat as escape character for {{
                            pos++;
                        else
                        {
                            pos--;
                            break;
                        }
                    }

                    Append(ch);
                }

                if (pos == len) break;
                pos++;
                if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
                int index = 0;
                do {
                    index = index * 10 + ch - '0';
                    pos++;
                    if (pos == len) FormatError();
                    ch = format[pos];
                } while (ch >= '0' && ch <= '9' && index < 1000000);
                if (index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
                while (pos < len && (ch = format[pos]) == ' ') pos++;
                bool leftJustify = false;
                int width = 0;
                if (ch == ',') {
                    pos++;
                    while (pos < len && format[pos] == ' ') pos++;

                    if (pos == len) FormatError();
                    ch = format[pos];
                    if (ch == '-') {
                        leftJustify = true;
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    }
                    if (ch < '0' || ch > '9') FormatError();
                    do {
                        width = width * 10 + ch - '0';
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    } while (ch >= '0' && ch <= '9' && width < 1000000);
                }

                while (pos < len && (ch = format[pos]) == ' ') pos++;
                Object arg = args[index];
                StringBuilder fmt = null;
                if (ch == ':') {
                    pos++;
                    p = pos;
                    i = pos;
                    while (true) {
                        if (pos == len) FormatError();
                        ch = format[pos];
                        pos++;
                        if (ch == '{')
                        {
                            if (pos < len && format[pos] == '{')  // Treat as escape character for {{
                                pos++;
                            else
                                FormatError();
                        }
                        else if (ch == '}')
                        {
                            if (pos < len && format[pos] == '}')  // Treat as escape character for }}
                                pos++;
                            else
                            {
                                pos--;
                                break;
                            }
                        }

                        if (fmt == null) {
                            fmt = new StringBuilder();
                        }
                        fmt.Append(ch);
                    }
                }
                if (ch != '}') FormatError();
                pos++;
                String sFmt = null;
                String s = null;
                if (cf != null) {
                    if (fmt != null) {
                        sFmt = fmt.ToString();
                    }
                    s = cf.Format(sFmt, arg, provider);
                }

                if (s == null) {
                    IFormattable formattableArg = arg as IFormattable;

#if FEATURE_LEGACYNETCF
                    if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                        // TimeSpan does not implement IFormattable in Mango
                        if(arg is TimeSpan) {
                            formattableArg = null;
                        }
                    }
#endif
                    if (formattableArg != null) {
                        if (sFmt == null && fmt != null) {
                            sFmt = fmt.ToString();
                        }

                        s = formattableArg.ToString(sFmt, provider);
                    } else if (arg != null) {
                        s = arg.ToString();
                    }
                }

                if (s == null) s = String.Empty;
                int pad = width - s.Length;
                if (!leftJustify && pad > 0) Append(' ', pad);
                Append(s);
                if (leftJustify && pad > 0) Append(' ', pad);
            }
            return this;
        }
Exemple #45
0
        private string ToString(string format, IFormatProvider provider)
        {
            if (this.IsEmpty)
            {
                return "Empty";
            }

            if (provider == null)
            {
                provider = CultureInfo.CurrentCulture;
            }

            if (format == null)
            {
                format = string.Empty;
            }

            string separator = ",";
            NumberFormatInfo numberFormat = provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;

            if (numberFormat != null && numberFormat.NumberDecimalSeparator == separator)
            {
                separator = ";";
            }

            string rectFormat = string.Format(
                "{{0:{0}}}{1}{{1:{0}}}{1}{{2:{0}}}{1}{{3:{0}}}",
                format,
                separator);

            return string.Format(provider, rectFormat, this.x, this.y, this.width, this.height);
        }
Exemple #46
0
        internal static StringBuilder FormatHelper(StringBuilder result, IFormatProvider provider, string format, params object[] args)
        {
            if (format == null)
                throw new ArgumentNullException("format");
            if (args == null)
                throw new ArgumentNullException("args");

            if (result == null)
            {
                /* Try to approximate the size of result to avoid reallocations */
                int i, len;

                len = 0;
                for (i = 0; i < args.Length; ++i)
                {
                    string s = args[i] as string;
                    if (s != null)
                        len += s.Length;
                    else
                        break;
                }
                result = new StringBuilder();
            }

            int ptr = 0;
            int start = ptr;
            var formatter = provider != null ? provider.GetFormat(typeof (ICustomFormatter)) as ICustomFormatter : null;

            while (ptr < format.Length)
            {
                char c = format[ptr ++];

                if (c == '{')
                {
                    result.Append(format, start, ptr - start - 1);

                    // check for escaped open bracket

                    if (format[ptr] == '{')
                    {
                        start = ptr ++;
                        continue;
                    }

                    // parse specifier

                    int n, width;
                    bool left_align;
                    string arg_format;

                    ParseFormatSpecifier(format, ref ptr, out n, out width, out left_align, out arg_format);
                    if (n >= args.Length)
                        throw new FormatException("Index (zero based) must be greater than or equal to zero and less than the size of the argument list.");

                    // format argument

                    object arg = args[n];

                    string str;
                    if (arg == null)
                        str = "";
                    else if (formatter != null)
                        str = formatter.Format(arg_format, arg, provider);
                    else
                        str = null;

                    if (str == null)
                    {
                        if (arg is IFormattable)
                            str = ((IFormattable)arg).ToString(arg_format, provider);
                        else
                            str = arg.ToString();
                    }

                    // pad formatted string and append to result
                    if (width > str.Length)
                    {
                        const char padchar = ' ';
                        int padlen = width - str.Length;

                        if (left_align)
                        {
                            result.Append(str);
                            result.Append(padchar, padlen);
                        }
                        else
                        {
                            result.Append(padchar, padlen);
                            result.Append(str);
                        }
                    }
                    else
                    {
                        result.Append(str);
                    }

                    start = ptr;
                }
                else if (c == '}' && ptr < format.Length && format[ptr] == '}')
                {
                    result.Append(format, start, ptr - start - 1);
                    start = ptr ++;
                }
                else if (c == '}')
                {
                    throw new FormatException("Input string was not in a correct format.");
                }
            }

            if (start < format.Length)
                result.Append(format, start, format.Length - start);

            return result;
        }
Exemple #47
0
        /// <include file='doc\StringBuilder.uex' path='docs/doc[@for="StringBuilder.AppendFormat4"]/*' />
        public StringBuilder AppendFormat(IFormatProvider provider, String format, params Object[] args) {
            if (format == null || args == null) {
                throw new ArgumentNullException((format==null)?"format":"args");
            }
            char[] chars = format.ToCharArray(0, format.Length);
            int pos = 0;
            int len = chars.Length;
            char ch = '\x0';

            ICustomFormatter cf = null;
            if (provider!=null) {
                   cf=(ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
                } 

            while (true) {
                int p = pos;
                int i = pos;
                while (pos < len) {
                    ch = chars[pos];
                
                    pos++;
                    if (ch == '}') 
                    {
                        if(pos < len && chars[pos]=='}') // Treat as escape character for }}
                            pos++;
                        else
                            FormatError();
                    }

                    if (ch == '{') 
                    {
                        if(pos < len && chars[pos]=='{') // Treat as escape character for {{
                            pos++;
                        else
                        {
                            pos--;
                            break;
                        }
                    }

                    chars[i++] = ch;
                }
                if (i > p) Append(chars, p, i - p);
                if (pos == len) break;
                pos++;
                if (pos == len || (ch = chars[pos]) < '0' || ch > '9') FormatError();
                int index = 0;
                do {
                    index = index * 10 + ch - '0';
                    pos++;
                    if (pos == len) FormatError();
                    ch = chars[pos];
                } while (ch >= '0' && ch <= '9' && index < 1000000);
                if (index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
                while (pos < len && (ch=chars[pos]) == ' ') pos++;
                bool leftJustify = false;
                int width = 0;
                if (ch == ',') {
                    pos++;
                    while (pos < len && chars[pos] == ' ') pos++;

                    if (pos == len) FormatError();
                    ch = chars[pos];
                    if (ch == '-') {
                        leftJustify = true;
                        pos++;
                        if (pos == len) FormatError();
                        ch = chars[pos];
                    }
                    if (ch < '0' || ch > '9') FormatError();
                    do {
                        width = width * 10 + ch - '0';
                        pos++;
                        if (pos == len) FormatError();
                        ch = chars[pos];
                    } while (ch >= '0' && ch <= '9' && width < 1000000);
                }

                while (pos < len && (ch=chars[pos]) == ' ') pos++;
                Object arg = args[index];
                String fmt = null;
                if (ch == ':') {
                    pos++;
                    p = pos;
                    i = pos;
                    while (true) {
                        if (pos == len) FormatError();
                        ch = chars[pos];
                        pos++;
                        if (ch == '{')
                        {
                            if(pos < len && chars[pos]=='{')  // Treat as escape character for {{
                                pos++;
                            else
                                FormatError();
                        }
                        else if (ch == '}')
                        {
                            if(pos < len && chars[pos]=='}')  // Treat as escape character for }}
                                pos++;
                            else
                            {
                                pos--;
                                break;
                            }
                        }

                        chars[i++] = ch;
                    }
                    if (i > p) fmt = new String(chars, p, i - p);
                }
                if (ch != '}') FormatError();
                pos++;
                String s = null;
                if (cf != null) {
                    s = cf.Format(fmt, arg, provider);
                }
 
                if (s==null) {
                    if (arg is IFormattable) {
                        s = ((IFormattable)arg).ToString(fmt, provider);
                    } else if (arg != null) {
                        s = arg.ToString();
                    }
                }

                if (s == null) s = String.Empty;
                int pad = width - s.Length;
                if (!leftJustify && pad > 0) Append(' ', pad);
                Append(s);
                if (leftJustify && pad > 0) Append(' ', pad);
            }
            return this;
        }
Exemple #48
0
        internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            int pos = 0;
            int len = format.Length;
            char ch = '\x0';
            StringBuilder unescapedItemFormat = null;

            ICustomFormatter cf = null;
            if (provider != null)
            {
                cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
            }

            while (true)
            {
                while (pos < len)
                {
                    ch = format[pos];

                    pos++;
                    if (ch == '}')
                    {
                        if (pos < len && format[pos] == '}') // Treat as escape character for }}
                            pos++;
                        else
                            FormatError();
                    }

                    if (ch == '{')
                    {
                        if (pos < len && format[pos] == '{') // Treat as escape character for {{
                            pos++;
                        else
                        {
                            pos--;
                            break;
                        }
                    }

                    Append(ch);
                }

                if (pos == len) break;
                pos++;
                if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
                int index = 0;
                do
                {
                    index = index * 10 + ch - '0';
                    pos++;
                    if (pos == len) FormatError();
                    ch = format[pos];
                } while (ch >= '0' && ch <= '9' && index < 1000000);
                if (index >= args.Length) throw new FormatException(SR.Format_IndexOutOfRange);
                while (pos < len && (ch = format[pos]) == ' ') pos++;
                bool leftJustify = false;
                int width = 0;
                if (ch == ',')
                {
                    pos++;
                    while (pos < len && format[pos] == ' ') pos++;

                    if (pos == len) FormatError();
                    ch = format[pos];
                    if (ch == '-')
                    {
                        leftJustify = true;
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    }
                    if (ch < '0' || ch > '9') FormatError();
                    do
                    {
                        width = width * 10 + ch - '0';
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    } while (ch >= '0' && ch <= '9' && width < 1000000);
                }

                while (pos < len && (ch = format[pos]) == ' ') pos++;
                Object arg = args[index];
                String itemFormat = null;
                if (ch == ':')
                {
                    pos++;
                    int startPos = pos;

                    while (true)
                    {
                        if (pos == len) FormatError();
                        ch = format[pos];
                        pos++;
                        if (ch == '}' || ch == '{')
                        {
                            if (ch == '{')
                            {
                                if (pos < len && format[pos] == '{')  // Treat as escape character for {{
                                    pos++;
                                else 
                                    FormatError();
                            }
                            else
                            {
                                if (pos < len && format[pos] == '}')  // Treat as escape character for }}
                                    pos++; 
                                else 
                                { 
                                    pos--; 
                                    break; 
                                } 
                            }

                            // Reaching here means the brace has been escaped 
                            // so we need to build up the format string in segments 
                            if (unescapedItemFormat == null)
                            {
                                unescapedItemFormat = new StringBuilder();
                            }
                            unescapedItemFormat.Append(format, startPos, pos - startPos - 1);
                            startPos = pos;
                        }
                    }

                    if (unescapedItemFormat == null || unescapedItemFormat.Length == 0) 
                    { 
                        if (startPos != pos) 
                        { 
                            // There was no brace escaping, extract the item format as a single string 
                            itemFormat = format.Substring(startPos, pos - startPos); 
                         } 
                    } 
                    else 
                    { 
                        unescapedItemFormat.Append(format, startPos, pos - startPos); 
                        itemFormat = unescapedItemFormat.ToString(); 
                        unescapedItemFormat.Clear(); 
                     }
                }
                if (ch != '}') FormatError();
                pos++;
                String s = null;
                if (cf != null)
                {
                    s = cf.Format(itemFormat, arg, provider);
                }

                if (s == null)
                {
                    IFormattable formattableArg = arg as IFormattable;
                    if (formattableArg != null)
                    {
                        s = formattableArg.ToString(itemFormat, provider);
                    }
                    else if (arg != null)
                    {
                        s = arg.ToString();
                    }
                }

                if (s == null) s = String.Empty;
                int pad = width - s.Length;
                if (!leftJustify && pad > 0) Append(' ', pad);
                Append(s);
                if (leftJustify && pad > 0) Append(' ', pad);
            }
            return this;
        }
Exemple #49
0
		string System.IFormattable.ToString (string format, IFormatProvider provider)
		{
			if (String.IsNullOrEmpty (format))
				format = null;

			if (provider != null) {
				ICustomFormatter cp = (ICustomFormatter) provider.GetFormat (typeof (ICustomFormatter));
				if (cp != null) {
					return String.Format ("{0}{1}{2}", cp.Format (format, x, provider), 
						cp.Format (null, ',', provider), cp.Format (format, y, provider));
				}
			}

			return String.Format ("{0},{1}", x.ToString (format, provider), y.ToString (format, provider));
		}
 public static DateTimeFormatInfo GetInstance(IFormatProvider provider) {
     // Fast case for a regular CultureInfo
     DateTimeFormatInfo info;
     CultureInfo cultureProvider = provider as CultureInfo;
     if (cultureProvider != null && !cultureProvider.m_isInherited)
     {
         return cultureProvider.DateTimeFormat;
     }
     // Fast case for a DTFI;
     info = provider as DateTimeFormatInfo;
     if (info != null) {
         return info;
     }
     // Wasn't cultureInfo or DTFI, do it the slower way
     if (provider != null) {
         info = provider.GetFormat(typeof(DateTimeFormatInfo)) as DateTimeFormatInfo;
         if (info != null) {
             return info;
         }
     }
     // Couldn't get anything, just use currentInfo as fallback
     return CurrentInfo;
 }
Exemple #51
0
        internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) {
            if (format == null) {
                throw new ArgumentNullException("format");
            }
            Contract.Ensures(Contract.Result<StringBuilder>() != null);
            Contract.EndContractBlock();

            int pos = 0;
            int len = format.Length;
            char ch = '\x0';

            ICustomFormatter cf = null;
            if (provider != null) {
                cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
            }

            while (true) {
                while (pos < len) {
                    ch = format[pos];

                    pos++;
                    if (ch == '}')
                    {
                        if (pos < len && format[pos] == '}') // Treat as escape character for }}
                            pos++;
                        else
                            FormatError();
                    }

                    if (ch == '{')
                    {
                        if (pos < len && format[pos] == '{') // Treat as escape character for {{
                            pos++;
                        else
                        {
                            pos--;
                            break;
                        }
                    }

                    Append(ch);
                }

                if (pos == len) break;
                pos++;
                if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
                int index = 0;
                do {
                    index = index * 10 + ch - '0';
                    pos++;
                    if (pos == len) FormatError();
                    ch = format[pos];
                } while (ch >= '0' && ch <= '9' && index < 1000000);
                if (index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
                while (pos < len && (ch = format[pos]) == ' ') pos++;
                bool leftJustify = false;
                int width = 0;
                if (ch == ',') {
                    pos++;
                    while (pos < len && format[pos] == ' ') pos++;

                    if (pos == len) FormatError();
                    ch = format[pos];
                    if (ch == '-') {
                        leftJustify = true;
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    }
                    if (ch < '0' || ch > '9') FormatError();
                    do {
                        width = width * 10 + ch - '0';
                        pos++;
                        if (pos == len) FormatError();
                        ch = format[pos];
                    } while (ch >= '0' && ch <= '9' && width < 1000000);
                }

                while (pos < len && (ch = format[pos]) == ' ') pos++;
                Object arg = args[index];
                StringBuilder fmt = null;
                if (ch == ':') {
                    pos++;
                    while (true) {
                        if (pos == len) FormatError();
                        ch = format[pos];
                        pos++;
                        if (ch == '{')
                        {
                            if (pos < len && format[pos] == '{')  // Treat as escape character for {{
                                pos++;
                            else
                                FormatError();
                        }
                        else if (ch == '}')
                        {
                            if (pos < len && format[pos] == '}')  // Treat as escape character for }}
                                pos++;
                            else
                            {
                                pos--;
                                break;
                            }
                        }

                        if (fmt == null) {
                            fmt = new StringBuilder();
                        }
                        fmt.Append(ch);
                    }
                }
                if (ch != '}') FormatError();
                pos++;
                String sFmt = null;
                String s = null;
                if (cf != null) {
                    if (fmt != null) {
                        sFmt = fmt.ToString();
                    }
                    s = cf.Format(sFmt, arg, provider);
                }

                if (s == null) {
                    IFormattable formattableArg = arg as IFormattable;

                    if (formattableArg != null) {
                        if (sFmt == null && fmt != null) {
                            sFmt = fmt.ToString();
                        }

                        s = formattableArg.ToString(sFmt, provider);
                    } else if (arg != null) {
                        s = arg.ToString();
                    }
                }

                if (s == null) s = String.Empty;
                int pad = width - s.Length;
                if (!leftJustify && pad > 0) Append(' ', pad);
                Append(s);
                if (leftJustify && pad > 0) Append(' ', pad);
            }
            return this;
        }
Exemple #52
0
		string IFormattable.ToString (string value, IFormatProvider formatProvider)
		{
			if (value == null)
				return ToString (formatProvider);

			if (formatProvider != null) {
				ICustomFormatter cp = (ICustomFormatter) formatProvider.GetFormat (typeof (ICustomFormatter));
				if (cp != null) {
					return String.Format ("sc#{0}{1} {2}{3} {4}{5} {6}", 
						cp.Format (value, A, formatProvider), cp.Format (value, ',', formatProvider),
						cp.Format (value, R, formatProvider), cp.Format (value, ',', formatProvider),
						cp.Format (value, G, formatProvider), cp.Format (value, ',', formatProvider),
						cp.Format (value, B, formatProvider));
				}
			}

			return String.Format ("sc#{0}{1} {2}{3} {4}{5} {6}", 
				A.ToString (value, formatProvider), ','.ToString (formatProvider),
				R.ToString (value, formatProvider), ','.ToString (formatProvider),
				G.ToString (value, formatProvider), ','.ToString (formatProvider),
				B.ToString (value, formatProvider));
		}
Exemple #53
0
        public override string ToString(string format, IFormatProvider provider)
        {
            if (provider != null)
            {
                ICustomFormatter formatter = provider.GetFormat(GetType()) as ICustomFormatter;
                if (formatter != null)
                    return formatter.Format(format, this, provider);
            }

            var builder = new System.Text.StringBuilder();
            DoToString(builder, format, 0);

            return builder.ToString();
        }
Exemple #54
0
		public string ToString (IFormatProvider provider)
		{
			if (provider == null)
				return ToString ();

			if (provider != null) {
				ICustomFormatter cp = (ICustomFormatter) provider.GetFormat (typeof (ICustomFormatter));
				if (cp != null) {
					return String.Format ("#{0}{1}{2}{3}", 	cp.Format ("X2", A, provider),
						cp.Format ("X2", R, provider), cp.Format ("X2", G, provider),
						cp.Format ("X2", B, provider));
				}
			}

			return String.Format ("#{0}{1}{2}{3}", 	A.ToString ("X2", provider), R.ToString ("X2", provider), 
				G.ToString ("X2", provider), B.ToString ("X2", provider));
		}
Exemple #55
0
 /// <include file='doc\DateTimeFormatInfo.uex' path='docs/doc[@for="DateTimeFormatInfo.GetInstance"]/*' />
 public static DateTimeFormatInfo GetInstance(IFormatProvider provider)
 {
     if (provider != null)
     {
         Object service = provider.GetFormat(typeof(DateTimeFormatInfo));
         if (service != null) return (DateTimeFormatInfo)service;
     }
     return (CurrentInfo);
 }
    public sbyte ToSByte(IFormatProvider provider)
    {
        bool toMinValue = true;

        if (provider != null)
        {
            TestFormatProvider format = provider.GetFormat(typeof(TestFormatProvider)) as TestFormatProvider;
            if ((format != null) && format.ToSByteMaxValue)
            {
                toMinValue = false;
            }
        }

        if (toMinValue)
        {
            return SByte.MinValue;
        }
        else
        {
            return SByte.MaxValue;
        }
    }
Exemple #57
0
        private const int Width_Limit = 1000000; // Note: -Width_Limit <  ArgAlign < Width_Limit

        internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) {
            if (format == null) {
                throw new ArgumentNullException("format");
            }
            Contract.Ensures(Contract.Result<StringBuilder>() != null);
            Contract.EndContractBlock();

            int pos = 0;
            int len = format.Length;
            char ch = '\x0';
            StringBuilder unescapedItemFormat = null;

            ICustomFormatter cf = null;
            if (provider != null) {
                cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
            }

            while (true) {
                while (pos < len) {
                    ch = format[pos];

                    pos++;
                    // Is it a closing brace?
                    if (ch == '}')
                    {
                        // Check next character (if there is one) to see if it is escaped. eg }}
                        if (pos < len && format[pos] == '}')
                            pos++;
                        else
                            // Otherwise treat it as an error (Mismatched closing brace)
                            FormatError();
                    }
                    // Is it a opening brace?
                    if (ch == '{')
                    {
                        // Check next character (if there is one) to see if it is escaped. eg {{
                        if (pos < len && format[pos] == '{')
                            pos++;
                        else
                        {
                            // Otherwise treat it as the opening brace of an Argument Hole.
                            pos--;
                            break;
                        }
                    }
                    // If it neither then treat the character as just text.
                    Append(ch);
                }

                //
                // Start of parsing of Argument Hole.
                // Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? }
                //
                if (pos == len) break;
                
                //
                //  Start of parsing required Index parameter.
                //  Index ::= ('0'-'9')+ WS*
                //
                pos++;
                // If reached end of text then error (Unexpected end of text)
                // or character is not a digit then error (Unexpected Character)
                if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
                int index = 0;
                do {
                    index = index * 10 + ch - '0';
                    pos++;
                    // If reached end of text then error (Unexpected end of text)
                    if (pos == len) FormatError();
                    ch = format[pos];
                    // so long as character is digit and value of the index is less than 1000000 ( index limit )
                } while (ch >= '0' && ch <= '9' && index < Index_Limit);

                // If value of index is not within the range of the arguments passed in then error (Index out of range)
                if (index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
                
                // Consume optional whitespace.
                while (pos < len && (ch = format[pos]) == ' ') pos++;
                // End of parsing index parameter.

                //
                //  Start of parsing of optional Alignment
                //  Alignment ::= comma WS* minus? ('0'-'9')+ WS*
                //
                bool leftJustify = false;
                int width = 0;
                // Is the character a comma, which indicates the start of alignment parameter.
                if (ch == ',') {
                    pos++;
 
                    // Consume Optional whitespace
                    while (pos < len && format[pos] == ' ') pos++;
                    
                    // If reached the end of the text then error (Unexpected end of text)
                    if (pos == len) FormatError();
                    
                    // Is there a minus sign?
                    ch = format[pos];
                    if (ch == '-') {
                        // Yes, then alignment is left justified.
                        leftJustify = true;
                        pos++;
                        // If reached end of text then error (Unexpected end of text)
                        if (pos == len) FormatError();
                        ch = format[pos];
                    }
 
                    // If current character is not a digit then error (Unexpected character)
                    if (ch < '0' || ch > '9') FormatError();
                    // Parse alignment digits.
                    do {
                        width = width * 10 + ch - '0';
                        pos++;
                        // If reached end of text then error. (Unexpected end of text)
                        if (pos == len) FormatError();
                        ch = format[pos];
                        // So long a current character is a digit and the value of width is less than 100000 ( width limit )
                    } while (ch >= '0' && ch <= '9' && width < Width_Limit);
                    // end of parsing Argument Alignment
                }

                // Consume optional whitespace
                while (pos < len && (ch = format[pos]) == ' ') pos++;

                //
                // Start of parsing of optional formatting parameter.
                //
                Object arg = args[index];
                String itemFormat = null;
                // Is current character a colon? which indicates start of formatting parameter.
                if (ch == ':') {
                    pos++;
                    int startPos = pos;

                    while (true) {
                        // If reached end of text then error. (Unexpected end of text)
                        if (pos == len) FormatError();
                        ch = format[pos];
                        pos++;

                        // Is character a opening or closing brace?
                        if (ch == '}' || ch == '{')
                        {
                            if (ch == '{')
                            {
                                // Yes, is next character also a opening brace, then treat as escaped. eg {{
                                if (pos < len && format[pos] == '{')
                                    pos++;
                                else
                                    // Error Argument Holes can not be nested.
                                    FormatError();
                            }
                            else
                            {
                                // Yes, is next character also a closing brace, then treat as escaped. eg }}
                                if (pos < len && format[pos] == '}')
                                    pos++;
                                else
                                {
                                    // No, then treat it as the closing brace of an Arg Hole.
                                    pos--;
                                    break;
                                }
                            }

                            // Reaching here means the brace has been escaped
                            // so we need to build up the format string in segments
                            if (unescapedItemFormat == null)
                            {
                                unescapedItemFormat = new StringBuilder();
                            }
                            unescapedItemFormat.Append(format, startPos, pos - startPos - 1);
                            startPos = pos;
                        }
                    }

                    if (unescapedItemFormat == null || unescapedItemFormat.Length == 0)
                    {
                        if (startPos != pos)
                        {
                            // There was no brace escaping, extract the item format as a single string
                            itemFormat = format.Substring(startPos, pos - startPos);
                        }
                    }
                    else
                    {
                        unescapedItemFormat.Append(format, startPos, pos - startPos);
                        itemFormat = unescapedItemFormat.ToString();
                        unescapedItemFormat.Clear();
                    }
                }
                // If current character is not a closing brace then error. (Unexpected Character)
                if (ch != '}') FormatError();
                // Construct the output for this arg hole.
                pos++;
                String s = null;
                if (cf != null) {
                    s = cf.Format(itemFormat, arg, provider);
                }

                if (s == null) {
                    IFormattable formattableArg = arg as IFormattable;

                    if (formattableArg != null) {
                        s = formattableArg.ToString(itemFormat, provider);
                    } else if (arg != null) {
                        s = arg.ToString();
                    }
                }
                // Append it to the final output of the Format String.
                if (s == null) s = String.Empty;
                int pad = width - s.Length;
                if (!leftJustify && pad > 0) Append(' ', pad);
                Append(s);
                if (leftJustify && pad > 0) Append(' ', pad);
                // Continue to parse other characters.
            }
            return this;
        }
Exemple #58
0
		public static DateTimeFormatInfo GetInstance(IFormatProvider provider)
		{
			if (provider != null) {
				DateTimeFormatInfo dtfi;
				dtfi = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
				if (dtfi != null)
					return dtfi;
			}
			
			return CurrentInfo;
		}
 public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) {
     // Fast case for a regular CultureInfo
     NumberFormatInfo info;
     CultureInfo cultureProvider = formatProvider as CultureInfo;
     if (cultureProvider != null && !cultureProvider.m_isInherited) {
         info = cultureProvider.numInfo;
         if (info != null) {
             return info;
         }
         else {
             return cultureProvider.NumberFormat;
         }
     }
     // Fast case for an NFI;
     info = formatProvider as NumberFormatInfo;
     if (info != null) {
         return info;
     }
     if (formatProvider != null) {
         info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
         if (info != null) {
             return info;
         }
     }
     return CurrentInfo;
 }
 public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args)
 {
     if (format == null || args == null)
     throw new ArgumentNullException(format == null ? "format" : "args");
       int index1 = 0;
       int length = format.Length;
       char ch = char.MinValue;
       ICustomFormatter customFormatter = (ICustomFormatter) null;
       if (provider != null)
     customFormatter = (ICustomFormatter) provider.GetFormat(typeof (ICustomFormatter));
       while (true)
       {
     bool flag;
     int repeatCount;
     do
     {
       if (index1 < length)
       {
     ch = format[index1];
     ++index1;
     if ((int) ch == 125)
     {
       if (index1 < length && (int) format[index1] == 125)
         ++index1;
       else
         StringBuilder.FormatError();
     }
     if ((int) ch == 123)
     {
       if (index1 >= length || (int) format[index1] != 123)
         --index1;
       else
         goto label_10;
     }
     else
       goto label_12;
       }
       if (index1 != length)
       {
     int index2 = index1 + 1;
     if (index2 == length || (int) (ch = format[index2]) < 48 || (int) ch > 57)
       StringBuilder.FormatError();
     int index3 = 0;
     do
     {
       index3 = index3 * 10 + (int) ch - 48;
       ++index2;
       if (index2 == length)
         StringBuilder.FormatError();
       ch = format[index2];
     }
     while ((int) ch >= 48 && (int) ch <= 57 && index3 < 1000000);
     if (index3 >= args.Length)
       throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
     while (index2 < length && (int) (ch = format[index2]) == 32)
       ++index2;
     flag = false;
     int num = 0;
     if ((int) ch == 44)
     {
       ++index2;
       while (index2 < length && (int) format[index2] == 32)
         ++index2;
       if (index2 == length)
         StringBuilder.FormatError();
       ch = format[index2];
       if ((int) ch == 45)
       {
         flag = true;
         ++index2;
         if (index2 == length)
           StringBuilder.FormatError();
         ch = format[index2];
       }
       if ((int) ch < 48 || (int) ch > 57)
         StringBuilder.FormatError();
       do
       {
         num = num * 10 + (int) ch - 48;
         ++index2;
         if (index2 == length)
           StringBuilder.FormatError();
         ch = format[index2];
       }
       while ((int) ch >= 48 && (int) ch <= 57 && num < 1000000);
     }
     while (index2 < length && (int) (ch = format[index2]) == 32)
       ++index2;
     object obj = args[index3];
     StringBuilder stringBuilder = (StringBuilder) null;
     if ((int) ch == 58)
     {
       int index4 = index2 + 1;
       while (true)
       {
         if (index4 == length)
           StringBuilder.FormatError();
         ch = format[index4];
         ++index4;
         if ((int) ch == 123)
         {
           if (index4 < length && (int) format[index4] == 123)
             ++index4;
           else
             StringBuilder.FormatError();
         }
         else if ((int) ch == 125)
         {
           if (index4 < length && (int) format[index4] == 125)
             ++index4;
           else
             break;
         }
         if (stringBuilder == null)
           stringBuilder = new StringBuilder();
         stringBuilder.Append(ch);
       }
       index2 = index4 - 1;
     }
     if ((int) ch != 125)
       StringBuilder.FormatError();
     index1 = index2 + 1;
     string format1 = (string) null;
     string str = (string) null;
     if (customFormatter != null)
     {
       if (stringBuilder != null)
         format1 = ((object) stringBuilder).ToString();
       str = customFormatter.Format(format1, obj, provider);
     }
     if (str == null)
     {
       IFormattable formattable = obj as IFormattable;
       if (formattable != null)
       {
         if (format1 == null && stringBuilder != null)
           format1 = ((object) stringBuilder).ToString();
         str = formattable.ToString(format1, provider);
       }
       else if (obj != null)
         str = obj.ToString();
     }
     if (str == null)
       str = string.Empty;
     repeatCount = num - str.Length;
     if (!flag && repeatCount > 0)
       this.Append(' ', repeatCount);
     this.Append(str);
       }
       else
     goto label_76;
     }
     while (!flag || repeatCount <= 0);
     goto label_75;
     label_10:
     ++index1;
     label_12:
     this.Append(ch);
     continue;
     label_75:
     this.Append(' ', repeatCount);
       }
     label_76:
       return this;
 }