public void GetInstance(IFormatProvider formatProvider, NumberFormatInfo expected) { NumberFormatInfo nfi = NumberFormatInfo.GetInstance(formatProvider); Assert.Equal(expected.CurrencyDecimalDigits, nfi.CurrencyDecimalDigits); Assert.Equal(expected.CurrencyDecimalSeparator, nfi.CurrencyDecimalSeparator); Assert.Equal(expected.CurrencyGroupSeparator, nfi.CurrencyGroupSeparator); Assert.Equal(expected.CurrencyGroupSizes, nfi.CurrencyGroupSizes); Assert.Equal(expected.CurrencyNegativePattern, nfi.CurrencyNegativePattern); Assert.Equal(expected.CurrencyPositivePattern, nfi.CurrencyPositivePattern); Assert.Equal(expected.CurrencySymbol, nfi.CurrencySymbol); Assert.Equal(expected.NaNSymbol, nfi.NaNSymbol); Assert.Equal(expected.NegativeInfinitySymbol, nfi.NegativeInfinitySymbol); Assert.Equal(expected.NegativeSign, nfi.NegativeSign); Assert.Equal(expected.NumberDecimalDigits, nfi.NumberDecimalDigits); Assert.Equal(expected.NumberDecimalSeparator, nfi.NumberDecimalSeparator); Assert.Equal(expected.NumberGroupSeparator, nfi.NumberGroupSeparator); Assert.Equal(expected.NumberGroupSizes, nfi.NumberGroupSizes); Assert.Equal(expected.NumberNegativePattern, nfi.NumberNegativePattern); Assert.Equal(expected.PercentDecimalDigits, nfi.PercentDecimalDigits); Assert.Equal(expected.PercentDecimalSeparator, nfi.PercentDecimalSeparator); Assert.Equal(expected.PercentGroupSeparator, nfi.PercentGroupSeparator); Assert.Equal(expected.PercentGroupSizes, nfi.PercentGroupSizes); Assert.Equal(expected.PercentNegativePattern, nfi.PercentNegativePattern); Assert.Equal(expected.PercentPositivePattern, nfi.PercentPositivePattern); Assert.Equal(expected.PercentSymbol, nfi.PercentSymbol); Assert.Equal(expected.PositiveInfinitySymbol, nfi.PositiveInfinitySymbol); Assert.Equal(expected.PerMilleSymbol, nfi.PerMilleSymbol); Assert.Equal(expected.PositiveSign, nfi.PositiveSign); }
/// <summary> Initializes all readonly configuration values </summary> static Configuration() { // Serializer: Binary = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Binary.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; Binary.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; Binary.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded; // DEFUALT FORMATTING FORMAT_DEFAULT = LogUtils.PrepareFormatString("[{ManagedThreadId:D2}] {Level,8} - {Message}");// <- this can NOT contain expressions FORMAT_METHOD = LogUtils.PrepareFormatString("{MethodType:%s.}{MethodName}{MethodArgs:(%s)}"); FORMAT_LOCATION = LogUtils.PrepareFormatString("{LogCurrent: executing %s}{Method: at %s@}{IlOffset:?}{FileLocation}"); FORMAT_FILELINE = LogUtils.PrepareFormatString("{FileName: in %s:line }{FileLine:?}"); FORMAT_FULLMESSAGE = LogUtils.PrepareFormatString("{Message}{Location}{Exception}"); FormatProvider = new EventDataFormatter(); CSharpTest.Net.Utils.ProcessInfo info = new CSharpTest.Net.Utils.ProcessInfo(); ProcessId = info.ProcessId; ProcessName = info.ProcessName; AppDomainName = info.AppDomainName; EntryAssembly = info.EntryAssembly.GetName().Name; IsDebugging = info.IsDebugging; DefaultLogFile = info.DefaultLogFile.Insert(info.DefaultLogFile.LastIndexOf('.'), "{0}"); }
/// <summary> /// Construct a sink that saves logs to the specified storage account. Properties are being send as data and the level is used as tag. /// </summary> /// <param name="batchSizeLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> public LogglySink(IFormatProvider formatProvider, int batchSizeLimit, TimeSpan period) : base (batchSizeLimit, period) { _formatProvider = formatProvider; _client = new LogglyClient(); }
// Parsing methods. public static short Parse(String s, NumberStyles style, IFormatProvider provider) { NumberParser.ValidateIntegerStyle(style); return Convert.ToInt16(NumberParser.ParseInt32 (s, style, NumberFormatInfo.GetInstance(provider), 32768)); }
/// <summary> /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level, category and format Repository. /// </summary> /// <param name="level">A description of the importance of the messages.</param> /// <param name="category">The category of the messages.</param> /// <param name="formatRepository">An <see cref="IFormatRepository"/> object that controls formatting.</param> public DebuggerWriter(int level, string category, IFormatProvider formatRepository) : base(formatRepository) { this.level = level; this.category = category; isOpen = true; }
/// <summary>Obtains the string representation of this Scea.VectorMath.BezierCurve structure /// with the specified formatting information</summary> /// <param name="format">Standard numeric format string characters valid for a floating point</param> /// <param name="formatProvider">The culture specific formatting provider</param> /// <returns>A <see cref="T:System.String"></see> representing the 3D Bezier curve</returns> public string ToString(string format, IFormatProvider formatProvider) { if (format == null && formatProvider == null) return m_ctrlPoints[0].X.ToString("R") + ", " + m_ctrlPoints[0].Y.ToString("R") + ", " + m_ctrlPoints[0].Z.ToString("R") + ", " + m_ctrlPoints[1].X.ToString("R") + ", " + m_ctrlPoints[1].Y.ToString("R") + ", " + m_ctrlPoints[1].Z.ToString("R") + ", " + m_ctrlPoints[2].X.ToString("R") + ", " + m_ctrlPoints[2].Y.ToString("R") + ", " + m_ctrlPoints[2].Z.ToString("R") + ", " + m_ctrlPoints[3].X.ToString("R") + ", " + m_ctrlPoints[3].Y.ToString("R") + ", " + m_ctrlPoints[3].Z.ToString("R"); return String.Format ( "({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11})", ((double)m_ctrlPoints[0].X).ToString(format, formatProvider), ((double)m_ctrlPoints[0].Y).ToString(format, formatProvider), ((double)m_ctrlPoints[0].Z).ToString(format, formatProvider), ((double)m_ctrlPoints[1].X).ToString(format, formatProvider), ((double)m_ctrlPoints[1].Y).ToString(format, formatProvider), ((double)m_ctrlPoints[1].Z).ToString(format, formatProvider), ((double)m_ctrlPoints[2].X).ToString(format, formatProvider), ((double)m_ctrlPoints[2].Y).ToString(format, formatProvider), ((double)m_ctrlPoints[2].Z).ToString(format, formatProvider), ((double)m_ctrlPoints[3].X).ToString(format, formatProvider), ((double)m_ctrlPoints[3].Y).ToString(format, formatProvider), ((double)m_ctrlPoints[3].Z).ToString(format, formatProvider) ); }
public bool LessThanEqualTo(string version, IFormatProvider provider) { Version v = ConvertToVersion(version, provider); return this._major < v.Major || (this._major == v.Major && this._minor < v.Minor) || (this._major == v.Major && this._minor == v.Minor && this._build < v._build); }
internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, object[] args) { if (format == null) throw new ArgumentNullException("format"); if (args == null) throw new ArgumentNullException("args"); this.result = result; this.provider = provider; this.format = format; this.args = args; this.numberOfArguments = args.Length; if (result == null) { // Try to approximate the size of result to avoid reallocations int i, len; len = 0; var argLength = args.Length; for (i = 0; i < argLength; ++i) { string s = GetArg(i) as string; if (s != null) len += s.Length; else break; } this.result = new StringBuilder(len + format.Length); } }
/// <summary> /// Default ctor /// </summary> internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, params object[] args) { this.result = result; this.provider = provider; this.format = format; this.args = args; if (format == null) throw new ArgumentNullException("format"); if (args == null) throw new ArgumentNullException("args"); if (this.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; } if (i == args.Length) this.result = new StringBuilder(len + format.Length); else this.result = new StringBuilder(); } }
/// <summary> /// Construct a <see cref="JsonFormatter"/>. /// </summary> /// <param name="omitEnclosingObject">If true, the properties of the event will be written to /// the output without enclosing braces. Otherwise, if false, each event will be written as a well-formed /// JSON object.</param> /// <param name="closingDelimiter">A string that will be written after each log event is formatted. /// If null, <see cref="Environment.NewLine"/> will be used. Ignored if <paramref name="omitEnclosingObject"/> /// is true.</param> /// <param name="renderMessage">If true, the message will be rendered and written to the output as a /// property named RenderedMessage.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> public JsonFormatter( bool omitEnclosingObject = false, string closingDelimiter = null, bool renderMessage = false, IFormatProvider formatProvider = null) { _omitEnclosingObject = omitEnclosingObject; _closingDelimiter = closingDelimiter ?? Environment.NewLine; _renderMessage = renderMessage; _formatProvider = formatProvider; _literalWriters = new Dictionary<Type, Action<object, bool, TextWriter>> { { typeof(bool), (v, q, w) => WriteBoolean((bool)v, w) }, { typeof(char), (v, q, w) => WriteString(((char)v).ToString(), w) }, { typeof(byte), WriteToString }, { typeof(sbyte), WriteToString }, { typeof(short), WriteToString }, { typeof(ushort), WriteToString }, { typeof(int), WriteToString }, { typeof(uint), WriteToString }, { typeof(long), WriteToString }, { typeof(ulong), WriteToString }, { typeof(float), WriteToString }, { typeof(double), WriteToString }, { typeof(decimal), WriteToString }, { typeof(string), (v, q, w) => WriteString((string)v, w) }, { typeof(DateTime), (v, q, w) => WriteDateTime((DateTime)v, w) }, { typeof(DateTimeOffset), (v, q, w) => WriteOffset((DateTimeOffset)v, w) }, { typeof(ScalarValue), (v, q, w) => WriteLiteral(((ScalarValue)v).Value, w) }, { typeof(SequenceValue), (v, q, w) => WriteSequence(((SequenceValue)v).Elements, w) }, { typeof(DictionaryValue), (v, q, w) => WriteDictionary(((DictionaryValue)v).Elements, w) }, { typeof(StructureValue), (v, q, w) => WriteStructure(((StructureValue)v).TypeTag, ((StructureValue)v).Properties, w) }, }; }
/// <summary> /// Adds a sink that writes log events as documents to a MongoDb database. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="databaseUrl">The URL of a created MongoDB collection that log events will be written to.</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="cappedMaxSizeMb">Max total size in megabytes of the created capped collection. (Default: 50mb)</param> /// <param name="cappedMaxDocuments">Max number of documents of the created capped collection.</param> /// <param name="collectionName">Name of the collection. Default is "log".</param> /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> public static LoggerConfiguration MongoDBCapped( this LoggerSinkConfiguration loggerConfiguration, string databaseUrl, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, long cappedMaxSizeMb = 50, long? cappedMaxDocuments = null, string collectionName = null, int batchPostingLimit = MongoDBSink.DefaultBatchPostingLimit, TimeSpan? period = null, IFormatProvider formatProvider = null) { if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration"); if (databaseUrl == null) throw new ArgumentNullException("databaseUrl"); var optionsBuilder = CollectionOptions.SetCapped(true).SetMaxSize(cappedMaxSizeMb * 1024 * 1024); if (cappedMaxDocuments.HasValue) { optionsBuilder = optionsBuilder.SetMaxDocuments(cappedMaxDocuments.Value); } var defaultedPeriod = period ?? MongoDBSink.DefaultPeriod; return loggerConfiguration.Sink( new MongoDBSink( databaseUrl, batchPostingLimit, defaultedPeriod, formatProvider, collectionName ?? MongoDBSink.DefaultCollectionName, optionsBuilder), restrictedToMinimumLevel); }
public static string NamedFormat(string format, IFormatProvider provider, object formatObject, bool throwExceptionIfNotFound) { if (format == null) throw new ArgumentNullException("format"); Regex r = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); List<object> formatValues = new List<object>(); string rewrittenFormat = r.Replace(format, delegate(Match m) { Group startGroup = m.Groups["start"]; Group propertyGroup = m.Groups["property"]; Group formatGroup = m.Groups["format"]; Group endGroup = m.Groups["end"]; string propertyName = propertyGroup.Value; formatValues.Add(GetObjectValue(propertyName, formatObject, throwExceptionIfNotFound)); return new string('{', startGroup.Captures.Count) + (formatValues.Count - 1) + formatGroup.Value + new string('}', endGroup.Captures.Count); }); return string.Format(provider, rewrittenFormat, formatValues.ToArray()); }
public static string FormatWith(this string format, IFormatProvider provider, params object[] args) { if (format == null) throw new ArgumentNullException("format"); return string.Format(provider, format, args); }
public static LoggerConfiguration Log4Net( this LoggerSinkConfiguration loggerConfiguration, LogEventLevel restrictedToMinimumLevel, IFormatProvider formatProvider) { return loggerConfiguration.Log4Net(null, restrictedToMinimumLevel, formatProvider); }
public StringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(formatProvider) { if (sb==null) throw new ArgumentNullException("sb", Environment.GetResourceString("ArgumentNull_Buffer")); Contract.EndContractBlock(); _sb = sb; _isOpen = true; }
/// <summary> /// Replacement for the String.Format method, that throws an exception /// when the count of arguments does not match the count of placeholders. /// <para> /// If format and/or arguments are null then still a string is returned. /// </para> /// </summary> /// <param name="formatProvider"> /// The format Provider. /// </param> /// <param name="format"> /// The format string. /// </param> /// <param name="args"> /// The arguments to the format string.. /// </param> /// <returns> /// Returns the fully formatted string, if successful In case of /// an error, the format string and all parameters added in a list /// will be returned. /// </returns> /// <remarks> /// Tries to format with String.Format. In case of an Exception the /// original format string and all parameters added in a list will /// be returned. /// </remarks> public static string SecureFormat(IFormatProvider formatProvider, string format, params object[] args) { if (format == null) { // no format string return string.Empty; } // no arguments, just use format if (args == null) { return format; } try { return string.Format(formatProvider, format, args); } catch (FormatException) { string result = "!!! FORMAT ERROR !!!! " + format + ": "; return args.Aggregate(result, (current, arg) => current + (arg + ", ")); } }
public string Format(string format, object arg, IFormatProvider formatProvider) { if (arg != null) { string fmt; switch (format) { case "S": // second fmt = String.Format(new HMSFormatter("{0} seconds", "{0} second"), "{0}", arg); break; case "M": // minute fmt = String.Format(new HMSFormatter("{0} minutes", "{0} minute"), "{0}", arg); break; case "H": // hour fmt = String.Format(new HMSFormatter("{0} hours", "{0} hour"), "{0}", arg); break; case "D": // day fmt = String.Format(new HMSFormatter("{0} days", "{0} day"), "{0}", arg); break; default: // plural/ singular fmt = String.Format((int)arg > 1 ? _plural : _singular, arg); // watch the cast to int here... break; } return fmt; } return String.Format(format, arg); }
public string Format(string format, object arg, IFormatProvider provider) { if (arg == null || format != "Hx") return String.Format(parent,"{0:" + format + "}", arg); StringBuilder hexString = new StringBuilder(); Stack<int> stack = new Stack<int>(); int popped,delta, dec, providerBase = 16; try { dec = (int)arg; } catch (InvalidCastException ex) { throw new InvalidCastException("DecimalToHexProvider must recieve numerical type",ex); } while (dec != 0) { stack.Push(dec); dec /= providerBase; } delta = popped = stack.Pop(); hexString.Append(hexCharacters[delta]); while (stack.Count > 0) { delta = stack.Peek() - popped * providerBase; hexString.Append(hexCharacters[delta]); popped = stack.Pop(); } return hexString.ToString(); }
internal static String Format(Exception exception, IFormatProvider formatProvider) { if (exception == null) return null; // push all inner exceptions onto stack var exceptionStack = new Stack<Exception>(); var currentException = exception; while (currentException != null) { exceptionStack.Push(currentException); currentException = currentException.InnerException; } // go through inner exceptions in reverse order var sb = new StringBuilder(); for (Int32 i = 1; exceptionStack.Count > 0; i++) { currentException = exceptionStack.Pop(); FormatSingleException(formatProvider, sb, currentException, i); } // that's it; return result return sb.ToString(); }
public static String ToString(Double value, SIUnit unit, String format, IFormatProvider formatProvider) { var unitStr = unit.Symbol; if (value != 0) { var scale = 0; var log10 = Math.Log10(value); if (log10 < 0) { value = MakeLarger(value, unit, out scale); } else if (log10 > 0) { value = MakeSmaller(value, unit, out scale); } if (scale != 0) { unitStr = Prefixes[scale].Symbol + unit.Symbol; } } return String.Format(formatProvider, "{0} {1}", value, unitStr); }
/// <summary> /// Render the value to the output. /// </summary> /// <param name="output">The output.</param> /// <param name="format">A format string applied to the value, or null.</param> /// <param name="formatProvider">A format provider to apply to the value, or null to use the default.</param> /// <seealso cref="LogEventPropertyValue.ToString(string, IFormatProvider)"/>. public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null) { if (output == null) throw new ArgumentNullException(nameof(output)); if (TypeTag != null) { output.Write(TypeTag); output.Write(' '); } output.Write("{ "); var allButLast = _properties.Length - 1; for (var i = 0; i < allButLast; i++) { var property = _properties[i]; Render(output, property, formatProvider); output.Write(", "); } if (_properties.Length > 0) { var last = _properties[_properties.Length - 1]; Render(output, last, formatProvider); } output.Write(" }"); }
/// <summary> /// Converts the value of a specified object to an equivalent string /// representation using specified format and the invariant-culture /// formatting information. /// </summary> /// <param name="format"> /// A format string containing formatting specifications. /// </param> /// <param name="arg">An object to format.</param> /// <param name="formatProvider"> /// An IFormatProvider object that supplies format information about /// the current instance. /// </param> /// <returns> /// The string representation of the value of arg, formatted as specified /// by format and the invariant-culture. /// </returns> public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null) { var convertible = arg as IConvertible; if (convertible != null) { switch (convertible.GetTypeCode()) { case TypeCode.Boolean: return GetBool((bool)arg); case TypeCode.DateTime: return GetDateTime((DateTime)arg); case TypeCode.Decimal: return GetDecimal((decimal)arg); case TypeCode.Double: return GetFloatingPoint((double)arg); case TypeCode.Single: return GetFloatingPoint((float)arg); } } } var formatter = new StringBuilder(); formatter.AppendFormat(CultureInfo.InvariantCulture, "{0:" + format + "}", arg); return formatter.ToString(); }
public string Format(string format, object arg, IFormatProvider formatProvider) { if (!(arg is DateTime)) throw new NotSupportedException(); var dt = (DateTime)arg; string suffix; if (dt.Day % 10 == 1) { suffix = "st"; } else if (dt.Day % 10 == 2) { suffix = "nd"; } else if (dt.Day % 10 == 3) { suffix = "rd"; } else { suffix = "th"; } return string.Format("{1}{2} {0:MMMM} {0:yyyy}", arg, dt.Day, suffix); }
/// <summary> /// Converts the value of a <see cref="TimeSpan"/> object to its equivalent natural string representation. /// </summary> /// <param name="timeSpan">A <see cref="TimeSpan"/>.</param> /// <param name="provider">An <see cref="IFormatProvider"/>.</param> /// <returns>The natural string representation of the <see cref="TimeSpan"/>.</returns> public static string ToNaturalString(this TimeSpan timeSpan, IFormatProvider provider) { List<string> parts = new List<string>(); // Days if (timeSpan.Days != 0) { parts.Add(GetStringWithUnits(timeSpan.Days, "Day", provider)); } // Hours if (timeSpan.Hours != 0 || parts.Count != 0) { parts.Add(GetStringWithUnits(timeSpan.Hours, "Hour", provider)); } // Minutes if (timeSpan.Minutes != 0 || parts.Count != 0) { parts.Add(GetStringWithUnits(timeSpan.Minutes, "Minute", provider)); } // Seconds parts.Add(GetStringWithUnits(timeSpan.Seconds, "Second", provider)); // Join parts return string.Join( Resources.ResourceManager.GetString("TimeSpanExtensionsUnitSeparator", provider), parts); }
/// <summary> /// Construct a sink that saves logs to the specified storage account. Properties are being send as data and the level is used as tag. /// </summary> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <param name="logKey">The log key as found on the loggr website.</param> /// <param name="apiKey">The api key as found on the loggr website.</param> /// <param name="useSecure">Use a SSL connection. By default this is false.</param> /// <param name="userNameProperty">Specifies the property name to read the username from. By default it is UserName.</param> public LoggrSink(IFormatProvider formatProvider, string logKey, string apiKey, bool useSecure = false, string userNameProperty = "UserName") { _formatProvider = formatProvider; _userNameProperty = userNameProperty; _client = new LogClient(logKey, apiKey, useSecure); }
/// <summary> /// Returns the string representation of this object</summary> /// <param name="format">Optional standard numeric format string for a floating point number. /// If null, "R" is used for round-trip support in case the string is persisted. /// http://msdn.microsoft.com/en-us/library/vstudio/dwhawy9k(v=vs.100).aspx </param> /// <param name="formatProvider">Optional culture-specific formatting provider. This is usually /// a CultureInfo object or NumberFormatInfo object. If null, the current culture is used. /// Use CultureInfo.InvariantCulture for persistence.</param> /// <returns>String representation of object</returns> public string ToString(string format, IFormatProvider formatProvider) { string listSeparator = StringUtil.GetNumberListSeparator(formatProvider); // For historic reasons, use "R" for round-trip support, in case this string is persisted. if (format == null) format = "R"; return String.Format( "{1}{0} {2}{0} {3}{0} {4}{0} {5}{0} {6}{0} {7}{0} {8}{0} {9}{0} {10}{0} {11}{0} {12}", listSeparator, m_ctrlPoints[0].X.ToString(format, formatProvider), m_ctrlPoints[0].Y.ToString(format, formatProvider), m_ctrlPoints[0].Z.ToString(format, formatProvider), m_ctrlPoints[1].X.ToString(format, formatProvider), m_ctrlPoints[1].Y.ToString(format, formatProvider), m_ctrlPoints[1].Z.ToString(format, formatProvider), m_ctrlPoints[2].X.ToString(format, formatProvider), m_ctrlPoints[2].Y.ToString(format, formatProvider), m_ctrlPoints[2].Z.ToString(format, formatProvider), m_ctrlPoints[3].X.ToString(format, formatProvider), m_ctrlPoints[3].Y.ToString(format, formatProvider), m_ctrlPoints[3].Z.ToString(format, formatProvider)); }
/// <summary> /// Converts the given string to a Int16. /// </summary> /// <exception cref="ArgumentNullException">The value can not be null.</exception> /// <exception cref="ArgumentNullException">The format provider can not be null.</exception> /// <param name="value">The string to convert.</param> /// <param name="formatProvider">The format provider.</param> /// <returns>Returns the converted Int16.</returns> public static Int16 ToInt16( this String value, IFormatProvider formatProvider ) { value.ThrowIfNull( nameof( value ) ); formatProvider.ThrowIfNull( nameof( formatProvider ) ); return Convert.ToInt16( value, formatProvider ); }
/// <summary> /// Initializes a new instance of the <see cref="DebugWriter"/> class with the specified level, category and format provider. /// </summary> /// <param name="level">A description of the importance of the messages.</param> /// <param name="category">The category of the messages.</param> /// <param name="formatProvider">An <see cref="IFormatProvider"/> object that controls formatting.</param> public DebugWriter(int level, string category, IFormatProvider formatProvider) : base(formatProvider) { this.level = level; this.category = category; this.isOpen = true; }
public string ToString(string format, IFormatProvider formatProvider) { if (format.Contains(",") || format.Contains(";")) { string[] fieldArray = format.Split(';')[0].Split(','); string separator = format.Split(';')[1]; List<string> fieldResults = new List<string>(); foreach (string field in fieldArray) { if (_dictionary.HasValueFor(field.Trim())) { fieldResults.Add(_dictionary.ValueFor(field.Trim()).ToString()); } } return string.Join(separator, fieldResults.ToArray()); } else if (_dictionary.HasValueFor(format)) { object value = _dictionary.ValueFor(format); return value == null ? null : value.ToString(); } return null; }
/// <summary> /// Parses this TextValue and converts it to a DateTime value. /// </summary> /// <returns>The parsed DateTime or January 1 1970 if the TextValue was not possible to parse.</returns> public override DateTime ToDateTime(IFormatProvider provider) { DateTime dt; if (!DateTime.TryParse(InternalValue, out dt)) dt = new DateTime(1970, 1, 1); return dt; }
byte IConvertible.ToByte(IFormatProvider provider) { return(Convert.ToByte(_value)); }
long IConvertible.ToInt64(IFormatProvider provider) { return(Convert.ToInt64(_value)); }
int IConvertible.ToInt32(IFormatProvider provider) { return(Convert.ToInt32(_value)); }
short IConvertible.ToInt16(IFormatProvider provider) { return(Convert.ToInt16(_value)); }
double IConvertible.ToDouble(IFormatProvider provider) { return(Convert.ToDouble(_value)); }
decimal IConvertible.ToDecimal(IFormatProvider provider) { return(Convert.ToDecimal(_value)); }
DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to DateTime is not supported."); }
/// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] IFormatProvider provider) { return(ToString(provider, 2)); }
/// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) { return(UnitParser.Default.Parse <ElectricConductivityUnit>(str, provider)); }
bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to bool is not supported."); }
public string Payment() { var culture = CultureInfo.GetCultureInfo("en-US"); IFormatProvider numericFormatProvider = culture.NumberFormat; var orderLayer = new OrderLayer(); var itemList = new ItemList(); itemList.items = new List <Item>(); foreach (var line in orderLayer.Order.Lines) { var item = new Item { currency = "TRY", description = line.ProductName, name = line.ProductName, price = line.Price.ToString("F2", numericFormatProvider), quantity = line.Quantity.ToString(), sku = line.ProductId.ToString(), tax = line.Tax.ToString("F2", numericFormatProvider) }; itemList.items.Add(item); } var payer = new Payer { payment_method = "paypal" }; var baseUrl = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Order/PaymentCallback/Paypal"; var redirUrl = new RedirectUrls { return_url = baseUrl + "?result=ok", cancel_url = baseUrl + "?result=fail" }; var details = new Details { fee = (orderLayer.Order.InstallmentFee + orderLayer.Order.PaymentFee).ToString("F2", numericFormatProvider), shipping = orderLayer.Order.ShipCost.ToString("F2", numericFormatProvider), tax = orderLayer.Order.TaxTotal.ToString("F2", numericFormatProvider), subtotal = orderLayer.Order.OrderTotal.ToString("F2", numericFormatProvider) }; var amount = new Amount { currency = "TRY", total = orderLayer.Order.GrandTotal.ToString("F2", numericFormatProvider), details = details }; var transactionList = new List <Transaction>(); transactionList.Add( new Transaction { invoice_number = orderLayer.Order.Id.ToString("00000000"), amount = amount, item_list = itemList } ); var payment = new PayPal.Api.Payment { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrl }; var paymenter = payment.Create(apiCtx); var links = paymenter.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { return(link.href); } } return(string.Empty); }
/// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricConductivityUnit unit) { return(UnitParser.Default.TryParse <ElectricConductivityUnit>(str, provider, out unit)); }
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) { return(format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 })); }
/// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="provider">Format to use for localization. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider) { return(UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider)); }
/// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "DateTime")); }
public string ToString(string format, IFormatProvider formatProvider) { return(string.Format("int3x2({0}, {1}, {2}, {3}, {4}, {5})", c0.x.ToString(format, formatProvider), c1.x.ToString(format, formatProvider), c0.y.ToString(format, formatProvider), c1.y.ToString(format, formatProvider), c0.z.ToString(format, formatProvider), c1.z.ToString(format, formatProvider))); }
/// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return(m_value); }
/// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return(Convert.DefaultToType((IConvertible)this, type, provider)); }
public bool TryParseNumber(ParseType s, NumberStyles style, IFormatProvider provider, out ulong result) => ulong.TryParse(s, style, provider, out result);
/// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return(Convert.ToSingle(m_value)); }
public static string Format(IFormatProvider provider, string format, params object[] args) { return(Default.Format(provider, format, args)); }
public override string ToString(string format, IFormatProvider formatProvider) { return(string.Empty); }
private Expression GetFunctionExpression <T>(string filter, ParameterExpression sourceParameter, ICollection <ParameterExpression> lambdaParameters, Type type, IFormatProvider formatProvider) { //Contract.Requires(filter != null); //Contract.Requires(sourceParameter != null); //Contract.Requires(lambdaParameters != null); var functionTokens = filter.GetFunctionTokens(); if (functionTokens == null) { return(null); } var left = CreateExpression <T>( functionTokens.Left, sourceParameter, lambdaParameters, type ?? GetExpressionType <T>(functionTokens, sourceParameter, lambdaParameters), formatProvider); var right = left == null ? null : CreateExpression <T>( functionTokens.Right, sourceParameter, lambdaParameters, GetFunctionParameterType(functionTokens.Operation) ?? left.Type, formatProvider); return(left == null ? null : GetFunction(functionTokens.Operation, left, right, sourceParameter, lambdaParameters)); }
public bool TryParseNumber(ParseType s, NumberStyles style, IFormatProvider provider, out sbyte result) => sbyte.TryParse(s, style, provider, out result);
private Expression GetArithmeticExpression <T>(string filter, ParameterExpression parameter, ICollection <ParameterExpression> lambdaParameters, Type type, IFormatProvider formatProvider) { //Contract.Requires(filter != null); //Contract.Requires(parameter != null); //Contract.Requires(lambdaParameters != null); var arithmeticToken = filter.GetArithmeticToken(); if (arithmeticToken == null) { return(null); } var type1 = type ?? GetExpressionType <T>(arithmeticToken, parameter, lambdaParameters); var leftExpression = CreateExpression <T>(arithmeticToken.Left, parameter, lambdaParameters, type1, formatProvider); var rightExpression = CreateExpression <T>(arithmeticToken.Right, parameter, lambdaParameters, type1, formatProvider); return(leftExpression == null || rightExpression == null ? null : GetLeftRightOperation(arithmeticToken.Operation, leftExpression, rightExpression)); }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, "Center: {0}, Extents: {1}", Center.ToString(), Extents.ToString()); }
private Expression CreateExpression <T>(string filter, ParameterExpression sourceParameter, ICollection <ParameterExpression> lambdaParameters, Type type, IFormatProvider formatProvider) { //Contract.Requires(filter != null); //Contract.Requires(sourceParameter != null); //Contract.Requires(lambdaParameters != null); if (string.IsNullOrWhiteSpace(filter)) { return(null); } var tokens = filter.GetTokens(); if (tokens.Any()) { return(GetTokenExpression <T>(sourceParameter, lambdaParameters, type, formatProvider, tokens)); } if (string.Equals(filter, "null", StringComparison.OrdinalIgnoreCase)) { return(Expression.Constant(null)); } var stringMatch = StringRx.Match(filter); if (stringMatch.Success) { return(Expression.Constant(stringMatch.Groups[1].Value.Replace("''", "'"), typeof(string))); } if (NegateRx.IsMatch(filter)) { var negateExpression = CreateExpression <T>( filter.Substring(1), sourceParameter, lambdaParameters, type, formatProvider); //Contract.Assert(negateExpression != null); if (SupportsNegate(negateExpression.Type)) { return(Expression.Negate(negateExpression)); } throw new InvalidOperationException("Cannot negate " + negateExpression); } var expression = GetAnyAllFunctionExpression <T>(filter, sourceParameter, lambdaParameters, formatProvider) ?? GetPropertyExpression <T>(filter, sourceParameter, lambdaParameters) ?? GetArithmeticExpression <T>(filter, sourceParameter, lambdaParameters, type, formatProvider) ?? GetFunctionExpression <T>(filter, sourceParameter, lambdaParameters, type, formatProvider) ?? GetParameterExpression(filter, type, formatProvider) ?? GetBooleanExpression(filter, formatProvider); if (expression == null) { throw new InvalidOperationException("Could not create expression from: " + filter); } return(expression); }
private Expression GetAnyAllFunctionExpression <T>(string filter, ParameterExpression sourceParameter, ICollection <ParameterExpression> lambdaParameters, IFormatProvider formatProvider) { //Contract.Requires(filter != null); //Contract.Requires(sourceParameter != null); //Contract.Requires(lambdaParameters != null); var functionTokens = filter.GetAnyAllFunctionTokens(); if (functionTokens == null) { return(null); } var propertyExpression = GetPropertyExpression <T>(functionTokens.Left, sourceParameter, lambdaParameters); var leftType = propertyExpression.Type; var left = CreateExpression <T>( functionTokens.Left, sourceParameter, lambdaParameters, leftType, formatProvider); // Create a new ParameterExpression from the lambda parameter and add to a collection to pass around var parameterName = functionTokens.Right.Substring(0, functionTokens.Right.IndexOf(":", StringComparison.InvariantCultureIgnoreCase)).Trim(); var lambdaParameter = Expression.Parameter(MethodProvider.GetIEnumerableImpl(leftType).GetGenericArguments()[0], parameterName); lambdaParameters.Add(lambdaParameter); var lambdaFilter = functionTokens.Right.Substring(functionTokens.Right.IndexOf(":", StringComparison.InvariantCultureIgnoreCase) + 1).Trim(); var lambdaType = GetFunctionParameterType(functionTokens.Operation) ?? (left != null ? left.Type : null); var isLambdaAnyAllFunction = lambdaFilter.GetAnyAllFunctionTokens() != null; var right = isLambdaAnyAllFunction ? GetAnyAllFunctionExpression <T>(lambdaFilter, lambdaParameter, lambdaParameters, formatProvider) : CreateExpression <T>(lambdaFilter, sourceParameter, lambdaParameters, lambdaType, formatProvider); return(left == null ? null : GetFunction(functionTokens.Operation, left, right, sourceParameter, lambdaParameters)); }
bool IConvertible.ToBoolean(IFormatProvider provider) { return(Convert.ToBoolean(Value, provider)); }
private Expression GetTokenExpression <T>(ParameterExpression parameter, ICollection <ParameterExpression> lambdaParameters, Type type, IFormatProvider formatProvider, ICollection <TokenSet> tokens) { //Contract.Requires(tokens != null); //Contract.Requires(parameter != null); //Contract.Requires(lambdaParameters != null); string combiner = null; Expression existing = null; foreach (var tokenSet in tokens) { if (string.IsNullOrWhiteSpace(tokenSet.Left)) { if (string.Equals(tokenSet.Operation, "not", StringComparison.OrdinalIgnoreCase)) { var right = CreateExpression <T>( tokenSet.Right, parameter, lambdaParameters, type ?? GetExpressionType <T>(tokenSet, parameter, lambdaParameters), formatProvider); return(right == null ? null : GetOperation(tokenSet.Operation, null, right)); } combiner = tokenSet.Operation; } else { var left = CreateExpression <T>( tokenSet.Left, parameter, lambdaParameters, type ?? GetExpressionType <T>(tokenSet, parameter, lambdaParameters), formatProvider); if (left == null) { return(null); } var rightExpressionType = tokenSet.Operation == "and" ? null : left.Type; var right = CreateExpression <T>(tokenSet.Right, parameter, lambdaParameters, rightExpressionType, formatProvider); if (existing != null && !string.IsNullOrWhiteSpace(combiner)) { var current = right == null ? null : GetOperation(tokenSet.Operation, left, right); existing = GetOperation(combiner, existing, current ?? left); } else if (right != null) { existing = GetOperation(tokenSet.Operation, left, right); } } } return(existing); }