/// <summary> /// Tries to parse the specified string. /// </summary> /// <param name="type">The target type.</param> /// <param name="s">The arguments.</param> /// <param name="provider">The format provider.</param> /// <param name="result">The result.</param> /// <returns> /// <c>true</c> if parsing successful, <c>false</c> otherwise. /// </returns> public static bool TryParse(Type type, string s, IFormatProvider provider, out object result) { try { var t1 = typeof(string); var t2 = provider.GetType(); var mi = type.GetMethods().FirstOrDefault(m => { var p = m.GetParameters(); return m.Name == "Parse" && p.Length == 2 && p[0].ParameterType.IsAssignableFrom(t1) && p[1].ParameterType.IsAssignableFrom(t2); }); if (mi == null) { result = null; return false; } result = mi.Invoke(null, parameters: new object[] { s, provider }); return true; } catch { result = null; return false; } }
public static object Good1(object x, IFormatProvider p) { if (x == null) throw new ArgumentNullException("x"); if (p == null) throw new ArgumentNullException("p"); return Convert.ChangeType(x, p.GetType(), p); }
/// <summary> /// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="IFormatProvider" />. If the /// format provider is null then the format object for the current thread is returned. If it's /// a CultureInfo, that's used for everything. If it's a DateTimeFormatInfo, that's used for /// format strings, day names etc but the invariant culture is used for text comparisons and /// resource lookups. Otherwise, <see cref="ArgumentException"/> is thrown. /// </summary> /// <param name="provider">The <see cref="IFormatProvider" />.</param> /// <exception cref="ArgumentException">The format provider cannot be used for Noda Time.</exception> /// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns> public static NodaFormatInfo GetInstance(IFormatProvider provider) { switch (provider) { case null: return(GetFormatInfo(CurrentInfo.CultureInfo)); case CultureInfo cultureInfo: return(GetFormatInfo(cultureInfo)); // Note: no caching for this case. It's a corner case anyway... we could add a cache later // if users notice a problem. case DateTimeFormatInfo dateTimeFormatInfo: return(new NodaFormatInfo(CultureInfo.InvariantCulture, dateTimeFormatInfo)); default: throw new ArgumentException($"Cannot use provider of type {provider.GetType().FullName} in Noda Time", nameof(provider)); } }
public async Task DoStuffAsync(int parameter) { System.Reflection.PropertyInfo[] local = _field.GetType().GetProperties(); List <Task> list = new List <Task>(); local.ToList().ForEach(p => list.Add(Task.Run(() => { if (p.Name.Length > parameter) { PrintName(); Console.WriteLine("Not big enough!"); } return; }))); foreach (Task t in list) { await t; } Console.WriteLine(NEVER); }
/// <summary> /// Determines which format to use from a format provider, preferring <paramref name="format"/>. /// </summary> /// <param name="formatProvider"> /// Target format provider. /// </param> /// <param name="format"> /// Preferred format. /// </param> /// <returns> /// The preferred format if it exists in the provider, otherwise the default format. If /// no format can be found, <c>null</c> is returned. /// </returns> public static string FormatToUse(this IFormatProvider formatProvider, string format) { if (formatProvider == null) { return(format); } if (format != null) { IEnumerable <SupportedFormat> supportedFormats = formatProvider.SupportedFormats(); if (supportedFormats.Any(_ => _.Format == format)) { return(format); } } var attribute = (DefaultFormatAttribute)Attribute.GetCustomAttribute(formatProvider.GetType(), typeof(DefaultFormatAttribute)); return((attribute != null) ? attribute.DefaultFormat : null); }
public string Format(string format, object arg, IFormatProvider formatProvider) { if (formatProvider.GetType() == this.GetType()) { return(string.Format(this.Culture, "{0:0.00}", arg).Replace(this.Culture.NumberFormat.NumberDecimalSeparator + "00", "")); } else { if (arg is IFormattable) { return(((IFormattable)arg).ToString(format, this.Culture)); } else if (arg != null) { return(arg.ToString()); } else { return(String.Empty); } } }
/// <summary> /// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="IFormatProvider" />. If the /// format provider is null then the format object for the current thread is returned. If it's /// a CultureInfo, that's used for everything. If it's a DateTimeFormatInfo, that's used for /// format strings, day names etc but the invariant culture is used for text comparisons and /// resource lookups. Otherwise, <see cref="ArgumentException"/> is thrown. /// </summary> /// <param name="provider">The <see cref="IFormatProvider" />.</param> /// <exception cref="ArgumentException">The format provider cannot be used for Noda Time.</exception> /// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns> public static NodaFormatInfo GetInstance(IFormatProvider provider) { // TODO(misc): Use C# 7 pattern matching for this... if (provider == null) { provider = CultureInfo.CurrentCulture; } var cultureInfo = provider as CultureInfo; if (cultureInfo != null) { return(GetFormatInfo(cultureInfo)); } // Note: no caching for this case. It's a corner case anyway... we could add a cache later // if users notice a problem. var dateTimeFormatInfo = provider as DateTimeFormatInfo; if (dateTimeFormatInfo != null) { return(new NodaFormatInfo(CultureInfo.InvariantCulture, dateTimeFormatInfo)); } throw new ArgumentException($"Cannot use provider of type {provider.GetType().FullName} in Noda Time", nameof(provider)); }
/// <summary> /// Formats the message for the TypeConversionException /// </summary> /// <param name="value">The value that the user tried to convert</param> /// <param name="defaultValue">The default value used</param> /// <param name="targetType">The target type</param> /// <param name="format">The format provider</param> /// <returns>A string containing the message for the generated TypeConversionException</returns> public static string FormatTypeConversionExceptionMesssage(object value, object defaultValue, Type targetType, IFormatProvider format) { string valueTypeName = (value != null) ? value.GetType().ToString() : "(undefined type)"; string valueString = (value != null) ? (IsDBNull(value) ? "[NULL]" : value.ToString()) : "(null)"; string defaultValueTypeName = (defaultValue != null) ? defaultValue.GetType().ToString() : "(undefined type)"; string defaultValueString = (defaultValue != null) ? (IsDBNull(defaultValue) ? "[NULL]" : defaultValue.ToString()) : "(null)"; string targetTypeName = (targetType != null) ? targetType.ToString() : "(undefined type)"; string formatProviderTypeName = (format != null) ? format.GetType().ToString() : "(undefined type)"; string cultureName = (format != null) ? format.ToString() : string.Empty; return(string.Format( "Error(s) occured while trying to convert value '{0}' (of type '{1}') to type '{2}' using default value '{3}' (of type '{4}') and format provider '{5}' (of type '{6}')", valueString, valueTypeName, targetTypeName, defaultValueString, defaultValueString, cultureName, formatProviderTypeName)); }
public static string DefaultFormat( this IFormatProvider formatProvider) { return(formatProvider?.GetType() .GetCustomAttribute <DefaultFormatAttribute>(true)?.DefaultFormat); }
/// <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"); } }
/// <summary> /// Returns the available formats from the target format provider. /// </summary> /// <param name="formatProvider"> /// Target format provider. /// </param> /// <returns> /// An enumeration of <see cref="SupportedFormat"/>. /// </returns> public static IEnumerable <SupportedFormat> SupportedFormats(this IFormatProvider formatProvider) { if (formatProvider == null) { return(IFormatProviderExtensions.NoSupportedFormats); } var attributes = (SupportedFormatAttribute[])Attribute.GetCustomAttributes(formatProvider.GetType(), typeof(SupportedFormatAttribute)); if (attributes.Length == 0) { return(IFormatProviderExtensions.NoSupportedFormats); } return(attributes.OrderBy(_ => _.Ordinal).Select(_ => _.SupportedFormat)); }
internal static bool HasCustomFormatter(IFormatProvider provider) { return (provider.GetType() != typeof(CultureInfo) && provider.GetFormat(typeof(ICustomFormatter)) != null); }
/// <summary> /// Converts the raw value of this instance to its equivalent Milliradian (NATO) representation using the specified format and format information. /// </summary> /// <param name="provider">An object that supplies specific formatting information.</param> /// <param name="format">A standard or custom numeric format string.</param> /// <returns></returns> public string ToMils(IFormatProvider provider, string format) { if (provider == null) { throw new ArgumentNullException(nameof(provider), "The argument cannot be null."); } if (provider is MilliradianFormatInfo == false) { throw new InvalidOperationException(string.Format("The IFormatProvider was not of the expected type '{0}', it was a '{1}'.", typeof(MilliradianFormatInfo).Name, provider.GetType().Name)); } return(this.ToString(provider, format)); }
/// <summary> /// Formats the message for the TypeConversionException /// </summary> /// <param name="value">The value that the user tried to convert</param> /// <param name="defaultValue">The default value used</param> /// <param name="targetType">The target type</param> /// <param name="format">The format provider</param> /// <returns>A string containing the message for the generated TypeConversionException</returns> public static string FormatTypeConversionExceptionMesssage(object value, object defaultValue, Type targetType, IFormatProvider format) { string valueTypeName = (value != null) ? value.GetType().ToString() : "(undefined type)"; string valueString = (value != null) ? (IsDBNull(value) ? "[NULL]" : value.ToString()) : "(null)"; string defaultValueTypeName = (defaultValue != null) ? defaultValue.GetType().ToString() : "(undefined type)"; string defaultValueString = (defaultValue != null) ? (IsDBNull(defaultValue) ? "[NULL]" : defaultValue.ToString()) : "(null)"; string targetTypeName = (targetType != null) ? targetType.ToString() : "(undefined type)"; string formatProviderTypeName = (format != null) ? format.GetType().ToString() : "(undefined type)"; string cultureName = (format != null) ? format.ToString() : string.Empty; return string.Format( "Error(s) occured while trying to convert value '{0}' (of type '{1}') to type '{2}' using default value '{3}' (of type '{4}') and format provider '{5}' (of type '{6}')", valueString, valueTypeName, targetTypeName, defaultValueString, defaultValueString, cultureName, formatProviderTypeName); }
public string Format(String format, Object obj, IFormatProvider provider) { // Display information about method call. string formatString = format ?? "<null>"; Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}", provider.GetType().Name, obj ?? "<null>", formatString); if (obj == null) { return(String.Empty); } // If this is a byte and the "R" format string, format it with Roman numerals. if (obj is Byte && formatString.ToUpper().Equals("R")) { Byte value = (Byte)obj; int remainder; int result; String returnString = String.Empty; // Get the hundreds digit(s) result = Math.DivRem(value, 100, out remainder); if (result > 0) { returnString = new String('C', result); } value = (Byte)remainder; // Get the 50s digit result = Math.DivRem(value, 50, out remainder); if (result == 1) { returnString += "L"; } value = (Byte)remainder; // Get the tens digit. result = Math.DivRem(value, 10, out remainder); if (result > 0) { returnString += new String('X', result); } value = (Byte)remainder; // Get the fives digit. result = Math.DivRem(value, 5, out remainder); if (result > 0) { returnString += "V"; } value = (Byte)remainder; // Add the ones digit. if (remainder > 0) { returnString += new String('I', remainder); } // Check whether we have too many X characters. int pos = returnString.IndexOf("XXXX"); if (pos >= 0) { int xPos = returnString.IndexOf("L"); if (xPos >= 0 & xPos == pos - 1) { returnString = returnString.Replace("LXXXX", "XC"); } else { returnString = returnString.Replace("XXXX", "XL"); } } // Check whether we have too many I characters pos = returnString.IndexOf("IIII"); if (pos >= 0) { if (returnString.IndexOf("V") >= 0) { returnString = returnString.Replace("VIIII", "IX"); } else { returnString = returnString.Replace("IIII", "IV"); } } return(returnString); } // Use default for all other formatting. if (obj is IFormattable) { return(((IFormattable)obj).ToString(format, CultureInfo.CurrentCulture)); } else { return(obj.ToString()); } }
public static CustomStringParsableWithFormatProvider Parse(string value, IFormatProvider formatProvider) { return(new CustomStringParsableWithFormatProvider(value + " " + formatProvider.GetType().Name)); }
//public string ToString(string format, IFormatProvider provider) //{ //} #endregion #region IFormattable Members //string IFormattable.ToString(string format, IFormatProvider formatProvider) //{ // throw new Exception("The method or operation is not implemented."); //} #endregion #region IFormattable Members /// <summary> /// Convert a runtime context to a specified format string /// </summary> /// <param name="format">Format string that determines who a context will be returned</param> /// <param name="formatProvider">Unique provider for this context</param> /// <returns>Formatted string</returns> /// <exception cref="InvalidOperationException">Thrown if formatProvider is not MachineContextFormatter</exception> public string ToString(string format, IFormatProvider formatProvider) { MachineContextFormatter fmt = formatProvider as MachineContextFormatter; if (fmt == null) { throw new InvalidOperationException(TextUtils.StringFormat("Unable to convert {0} to RunTimeContextFormatter", formatProvider.GetType().FullName)); } return fmt.Format(format, this, formatProvider); }
public string Format(string format, object arg, IFormatProvider formatProvider) { Console.WriteLine("myID is " + myID + ", Format called with formatProvider: " + formatProvider.GetType().AssemblyQualifiedName); int baseNumber; string thisFmt = string.Empty; if (!String.IsNullOrEmpty(format)) thisFmt = format.Length > 1 ? format.Substring(0, 1) : format; byte[] bytes; if (arg is sbyte) { string byteString = ((sbyte)arg).ToString("X2"); bytes = new byte[1] { Byte.Parse(byteString, NumberStyles.HexNumber) }; } else if (arg is byte) { bytes = new byte[1] { (byte)arg }; } else if (arg is short) { bytes = BitConverter.GetBytes((short)arg); } else if (arg is int) { bytes = BitConverter.GetBytes((int)arg); } else if (arg is long) { bytes = BitConverter.GetBytes((long)arg); } else if (arg is ushort) { bytes = BitConverter.GetBytes((ushort)arg); } else if (arg is uint) { bytes = BitConverter.GetBytes((uint)arg); } else if (arg is ulong) { bytes = BitConverter.GetBytes((ulong)arg); } else if (arg is BigInteger) { bytes = ((BigInteger)arg).ToByteArray(); } else { try { return HandleOtherFormats(format, arg); } catch (FormatException e) { throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e); } } switch (thisFmt.ToUpper()) { // Binary formatting. case "B": baseNumber = 2; break; case "O": baseNumber = 8; break; case "H": baseNumber = 16; break; default: try { return HandleOtherFormats(format, arg); } catch (FormatException e) { throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e); } } string numericString = string.Empty; //Calculate the minimum required number of characters to display a value to a certain base. double numChars = Math.Log(256, baseNumber); int numCharsAsInt = (int)(numChars + 0.5d); string[] array = new string[4]; Console.WriteLine("Lower bound: " + array.GetLowerBound(0) + ", Upper bound: " + array.GetUpperBound(0)); for (int ctr = bytes.GetUpperBound(0); ctr >= bytes.GetLowerBound(0); ctr--) { string byteString = Convert.ToString(bytes[ctr], baseNumber); byteString = new String('0', numCharsAsInt - byteString.Length) + byteString; numericString += byteString + " "; } return numericString.Trim(); }
//public string ToString(string format, IFormatProvider provider) //{ //} #endregion #region IFormattable Members //string IFormattable.ToString(string format, IFormatProvider formatProvider) //{ // throw new Exception("The method or operation is not implemented."); //} #endregion #region IFormattable Members /// <summary> /// Convert a runtime context to a specified format string /// </summary> /// <param name="format">Format string that determines who a context will be returned</param> /// <param name="formatProvider">Unique provider for this context</param> /// <returns>Formatted string</returns> /// <exception cref="InvalidOperationException">Thrown if formatProvider is not MachineContextFormatter</exception> public string ToString(string format, IFormatProvider formatProvider) { MachineContextFormatter fmt = formatProvider as MachineContextFormatter; if (fmt == null) { throw new InvalidOperationException(TextUtils.StringFormat("Unable to convert {0} to RunTimeContextFormatter", formatProvider.GetType().FullName)); } return(fmt.Format(format, this, formatProvider)); }
public string ToString(string format, IFormatProvider formatProvider) { return("Formatted: " + format + ", " + (formatProvider == null ? "null formatProvider" : formatProvider.GetType().FullName)); }
public string ToString(string format, IFormatProvider formatProvider) { return("Formatted: " + (!string.IsNullOrEmpty(format) ? format + ", " : "") + formatProvider.GetType().Name); }