public override void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { if (Errors == null) Errors = new List<ValidationError>(); Errors.Add(Validator.CreateError(message, errorType, schema, value, childErrors)); }
public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { ValidationError error = CreateError(message, errorType, schema, value, childErrors); // shared cache information that could be read/populated from multiple threads // lock to ensure that only one thread writes known schemas if (Schema.KnownSchemas.Count == 0) { lock (Schema.KnownSchemas) { if (Schema.KnownSchemas.Count == 0) { JSchemaDiscovery discovery = new JSchemaDiscovery(Schema.KnownSchemas, KnownSchemaState.External); discovery.Discover(Schema, null); } } } PopulateSchemaId(error); SchemaValidationEventHandler handler = ValidationEventHandler; if (handler != null) handler(_publicValidator, new SchemaValidationEventArgs(error)); else throw JSchemaValidationException.Create(error); }
public static byte[] NumericFormating(IFormattable doubleNum, Encoding charEncoding, int fieldLength, int sizeDecimalPart) { int sizeWholePart = fieldLength - (sizeDecimalPart > 0 ? (sizeDecimalPart + 1) : 0); StringBuilder format = new StringBuilder(fieldLength); for (int i = 0; i < sizeWholePart; i++) { format.Append(i+1== sizeWholePart ? "0":"#"); } if (sizeDecimalPart > 0) { format.Append("."); for (int i = 0; i < sizeDecimalPart; i++) { format.Append("0"); } } return textPadding( doubleNum.ToString(format.ToString(), NumberFormatInfo.InvariantInfo), charEncoding, fieldLength, ALIGN_RIGHT); }
public static void AddParameter(this HttpRequestMessage request, string key, IFormattable value) { if (value != null) { request.AddParameter(key, value.ToString(null, CultureInfo.InvariantCulture)); } }
public GiveCommand(IFormattable player, Asset item, int? amount = null, int? data = null, DataTag dataTag = null) { if (player == null) throw new ArgumentNullException("player"); if (!(player is PlayerSelector || player is Player)) throw new ArgumentException("player must be a PlayerSelector or Player.", "player"); if (item == null) throw new ArgumentNullException("item"); if (item.Type == AssetType.Entity) throw new ArgumentException("item must have a type of Item or Block.", "item"); if (amount < 1 || amount > 64) throw new ArgumentException("amount must be between 1 and 64, inclusive.", "amount"); Player = player; Item = item; Amount = amount; Data = data; DataTag = dataTag; }
internal virtual void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { // mark all parent SchemaScopes as invalid Scope current = this; SchemaScope parentSchemaScope; while ((parentSchemaScope = current.Parent as SchemaScope) != null) { if (!parentSchemaScope.IsValid) break; parentSchemaScope.IsValid = false; current = parentSchemaScope; } Context.RaiseError(message, errorType, schema, value, childErrors); }
public string Format(string format, object arg, IFormatProvider formatProvider) { string s; IFormattable formattable = arg as IFormattable; if (formattable == null) { s = arg.ToString(); } else { s = formattable.ToString(format, formatProvider); } if (arg.GetType() == typeof(int)) { return("<B>" + s + "</B>"); } return(s); }
internal static ValidationError CreateValidationError(IFormattable message, ErrorType errorType, JSchema schema, Uri schemaId, object value, IList <ValidationError> childErrors, IJsonLineInfo lineInfo, string path) { ValidationError error = new ValidationError(); error._formattable = message; error.ErrorType = errorType; error.Path = path; if (lineInfo != null) { error.LineNumber = lineInfo.LineNumber; error.LinePosition = lineInfo.LinePosition; } error.Schema = schema; error.SchemaId = schemaId; error.SchemaBaseUri = schema.BaseUri; error.Value = value; error.ChildErrors = childErrors; return(error); }
private static string FormatScalarValue(object value, IFormatProvider formatProvider) { if (value is string) { return((string)value); } IFormattable formattable = value as IFormattable; if (formattable != null) { string format = null; if (value is float || value is double) { format = "R"; } return(formattable.ToString(format, formatProvider)); } return(value.ToString()); }
public virtual void WriteLine(object value) { if (value == null) { this.WriteLine(); } else { IFormattable formattable = value as IFormattable; if (formattable != null) { this.WriteLine(formattable.ToString(null, this.FormatProvider)); } else { this.WriteLine(value.ToString()); } } }
internal virtual void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList <ValidationError> childErrors) { // mark all parent SchemaScopes as invalid Scope current = this; SchemaScope parentSchemaScope; while ((parentSchemaScope = current.Parent) != null) { if (!parentSchemaScope.IsValid) { break; } parentSchemaScope.IsValid = false; current = parentSchemaScope; } Context.RaiseError(message, errorType, schema, value, childErrors); }
/// <summary> /// 将对象格式化为指定的东亚文化表示形式。 /// </summary> /// <param name="format">格式类型。</param> /// <param name="arg">将被格式化的数据。</param> /// <param name="formatProvider">格式提供者。</param> /// <param name="culture">区域语言类型。</param> /// <returns>用东亚语言格式化过的本地化字符串。</returns> /// <exception cref="ArgumentNullException"><paramref name="format"/>,<paramref name="arg"/> 或者 <paramref name="culture"/> 是一个空引用。 </exception> /// <exception cref="ArgumentException">localFmt 在此区域语言中不被支持。 </exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="arg"/> 超出范围。</exception> /// <exception cref="ArgumentException"><paramref name="arg"/> 是一个无效类型。</exception> public static string FormatWithCulture(string format, object arg, IFormatProvider formatProvider, CultureInfo culture) { if (format == null) { throw new ArgumentNullException("format"); } if (arg == null) { throw new ArgumentNullException("arg"); } if (culture == null) { throw new ArgumentNullException("culture"); } if ((!format.Equals("L") && !format.Equals("Ln")) && (!format.Equals("Lt") && !format.Equals("Lc"))) { IFormattable formattable = arg as IFormattable; if (formattable == null) { return(arg.ToString()); } return(formattable.ToString(format, formatProvider)); } EastAsiaFormatter formatter = EastAsiaFormatter.Create(culture, format); if (formatter == null) { throw new ArgumentException("参数 format 的格式不正确。"); } Type type = arg.GetType(); if ((((type != typeof(double)) && (type != typeof(float))) && ((type != typeof(int)) && (type != typeof(uint)))) && ((((type != typeof(long)) && (type != typeof(ulong))) && ((type != typeof(short)) && (type != typeof(ushort)))) && (((type != typeof(sbyte)) && (type != typeof(byte))) && (type != typeof(decimal))))) { throw new ArgumentException("参数 arg 的类型不正确。"); } double num = Convert.ToDouble(arg, null); if (formatter.CheckOutOfRange(num)) { throw new ArgumentOutOfRangeException("arg"); } return(formatter.ConvertToLocalizedText(Convert.ToDecimal(arg, null))); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { String valueString = "<null>"; if (value != null) { IFormattable formattableValue = value as IFormattable; if (formattableValue != null) { valueString = formattableValue.ToString((string)parameter, null); } else { valueString = value.ToString(); } } return(valueString); }
private void AddObjectContentToHashBuilder(object content) { if (content != null) { IFormattable formattable = content as IFormattable; if (formattable != null) { this.m_hashSourceBuilder.AppendLine(formattable.ToString((string)null, (IFormatProvider)CultureInfo.InvariantCulture)); } else { this.m_hashSourceBuilder.AppendLine(content.ToString()); } } else { this.m_hashSourceBuilder.AppendLine("NULL"); } }
public override object ConvertFrom(object source, CultureInfo culture) { if (source is string) { return((string)source); } if (source == null) { return(string.Empty); } if ((culture != null) && (culture != CultureInfo.CurrentCulture)) { IFormattable formattable = source as IFormattable; if (formattable != null) { return(formattable.ToString(null, culture)); } } return(source.ToString()); }
public static String ToString <T>(this List <T> l, String fmt) { String retVal = String.Empty; foreach (T item in l) { IFormattable ifmt = item as IFormattable; if (ifmt != null) { retVal += String.Format("{0}{1}", String.IsNullOrEmpty(retVal) ? "" : ", ", ifmt.ToString(fmt, null)); } else { retVal += ToString2(l); } } return(String.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }"); }
/// <summary> /// Writes the line. /// </summary> /// <param name="ed">The ed.</param> /// <param name="value">The value.</param> public static void WriteLine(this Editor ed, object value) { if (value == null) { ed.WriteLine(); } else { IFormattable formattable = value as IFormattable; if (formattable != null) { ed.Write(formattable.ToString(null, formatProvider)); } else { ed.WriteMessage(value.ToString()); } ed.WriteLine(); } }
/// <summary> /// Formats the contents of an XML element and returns the result. /// </summary> /// <param name="element">The elements whose contents are to be formatted.</param> /// <returns>The formatted contents of the elements.</returns> /// <remarks> /// The format to be used is determined by the <c>type</c> and <c>spec</c> /// attributes of the element. The <c>type</c> attribute should be the fully /// qualified type name of an <see cref="IFormattable"/> type. The <c>spec</c> /// attribute defines the format string to be used when formatting the contents. /// If <c>type</c> or <c>spec</c> are not defined or if <c>type</c> resovles to /// a type that is not <see cref="IFormattable"/>, the contents are not formatted /// and are returned as-is. /// </remarks> public static object Format(this XElement element) { Type elementType = Type.GetType((string)element.Attribute("type"), false); string formatString = (string)element.Attribute("spec"); if (elementType is null || formatString is null) { return(element.Nodes()); } if (!typeof(IFormattable).IsAssignableFrom(elementType)) { return(element.Nodes()); } string value = (string)element; IFormattable formattable = (IFormattable)Convert.ChangeType(value, elementType); return(new XText(formattable.ToString(formatString, null))); }
private static string BindProperty(object property, string propertyName, string format, IFormatProvider provider) { string retValue = String.Empty; if (propertyName.Contains(".")) { string leftPropertyName = propertyName.Substring(0, propertyName.IndexOf(".", StringComparison.Ordinal)); PropertyInfo[] arrayProperties = property.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in arrayProperties) { if (propertyInfo.Name == leftPropertyName) { retValue = BindProperty(propertyInfo.GetValue(property, null), propertyName.Substring(propertyName.IndexOf(".", StringComparison.Ordinal) + 1), format, provider); break; } } } else { Type propertyType; PropertyInfo propertyInfo; propertyType = property.GetType(); propertyInfo = propertyType.GetProperty(propertyName); var obj = propertyInfo.GetValue(property, null); IFormattable fmt = obj as IFormattable; if (fmt != null) { retValue = fmt.ToString(format, provider); } else { retValue = obj.ToString(); } } return(retValue); }
public void TestExceptionFromSuppressor() { string source = "class C { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var expectedException = new NotImplementedException(); var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var suppressor = new DiagnosticSuppressorThrowsExceptionFromReportedSuppressions(analyzer.Descriptor.Id, expectedException); var exceptions = new List <Exception>(); EventHandler <FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception == expectedException) { exceptions.Add(e.Exception); } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => exceptions[0])} -----"; var analyzersAndSuppressors = new DiagnosticAnalyzer[] { analyzer, suppressor }; VerifyAnalyzerDiagnostics(compilation, analyzersAndSuppressors, Diagnostic("AD0001").WithArguments(suppressor.ToString(), typeof(NotImplementedException).FullName, new NotImplementedException().Message, context).WithLocation(1, 1), Diagnostic("ID1000", "class C { }").WithLocation(1, 1)); VerifySuppressedDiagnostics(compilation, analyzersAndSuppressors); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } }
public override string ReadText() { object value = jsonReader.Value; switch (currentToken) { case JsonToken.Null: return(null); case JsonToken.PropertyName: case JsonToken.String: return(value as string); case JsonToken.Int: case JsonToken.UInt: case JsonToken.Long: case JsonToken.ULong: case JsonToken.Boolean: { IFormattable formattable2 = value as IFormattable; if (formattable2 != null) { return(formattable2.ToString(null, CultureInfo.InvariantCulture)); } return(value.ToString()); } case JsonToken.Double: { IFormattable formattable = value as IFormattable; if (formattable != null) { return(formattable.ToString("R", CultureInfo.InvariantCulture)); } return(value.ToString()); } default: throw new AmazonClientException("We expected a VALUE token but got: " + currentToken); } }
private static string SerializeObject(object o) { TypeCode typeCode = TypeCode.Empty; string arg = string.Empty; Array array = o as Array; if (o == null) { arg = "0"; } else if (array != null) { typeCode = TypeCode.Object; arg = ConfigurationDictionary.EncodeArray(array); } else if (o is ExDateTime) { typeCode = TypeCode.DateTime; arg = ((ExDateTime)o).ToBinary().ToString(CultureInfo.InvariantCulture); } else { typeCode = Type.GetTypeCode(o.GetType()); int i; for (i = 0; i < ConfigurationDictionary.simpleSerializableTypes.Length; i++) { if (ConfigurationDictionary.simpleSerializableTypes[i] == typeCode) { IFormattable formattable = o as IFormattable; arg = ((formattable != null) ? formattable.ToString(null, CultureInfo.InvariantCulture) : o.ToString()); break; } } if (i == ConfigurationDictionary.simpleSerializableTypes.Length) { ExTraceGlobals.StorageTracer.TraceError <Type>(0L, "ConfigurationDictionary::SerializeObject. The type '{0}' is not supported by user configuration for serialization.", o.GetType()); throw new NotSupportedException(ServerStrings.ExTypeSerializationNotSupported(o.GetType())); } } return(string.Format("{0}{1}{2}", (int)typeCode, '-', arg)); }
public void AppendFormatted(StringBuilder sb) { foreach (KeyValuePair <string, object> entry in GetCurrentApplicationStateInfo()) { sb.Append(entry.Key); sb.Append(": "); if (entry.Value == null) { sb.AppendLine("<null>"); } else { IFormattable f = entry.Value as IFormattable; if (f != null) { try { sb.AppendLine(f.ToString(null, CultureInfo.InvariantCulture)); } catch (Exception ex) { sb.AppendLine("--> Exception thrown by IFormattable.ToString:"); sb.AppendLine(ex.ToString()); } } else { try { sb.AppendLine(entry.Value.ToString()); } catch (Exception ex) { sb.AppendLine("--> Exception thrown by ToString:"); sb.AppendLine(ex.ToString()); } } } } }
static string PostfixedForCurrency(IFormattable bigInteger, string[] currencyPostfixList) { var s = bigInteger.ToString(); var sLen = s.Length; var sb = new StringBuilder(); var omitZero = false; var postfixAppended = false; var postfixCount = 0; for (var i = 0; i < s.Length; i++) { if (s[i] != '0' || omitZero == false) { if (postfixAppended) { sb.Append(' '); postfixAppended = false; } sb.Append(s[i]); omitZero = false; } var irev = s.Length - i - 1; var postfixStr = currencyPostfixList[irev < currencyPostfixList.Length ? irev : currencyPostfixList.Length - 1]; if (postfixStr != null && omitZero == false) { sb.Append(postfixStr); omitZero = true; postfixCount++; if (postfixCount >= 3) { break; } postfixAppended = true; } } return(sb.ToString()); }
/// <summary> /// Handles formatting for objects other than matrices. /// </summary> private static string handleOtherFormats(string format, object arg, CultureInfo culture) { try { IFormattable obj = arg as IFormattable; if (obj != null) { return(obj.ToString(format, culture)); } else if (arg != null) { return(arg.ToString()); } } catch (FormatException e) { throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e); } return(String.Empty);; }
/// <summary> /// Writes the specified value to the specified key. Keys are organized hierarchially and behave /// like file paths. Use the normal path separator chars to address keys in keys. /// </summary> /// <typeparam name="T">The value's Type.</typeparam> /// <param name="key">The key that defines to write the value to.</param> /// <param name="value">The value to write</param> /// <seealso cref="WriteValue(string, string)"/> public void WriteValue <T>(string key, T value) { string valStr = value as string; if (valStr != null) { this.WriteValue(key, valStr); return; } IFormattable valFormattable = value as IFormattable; if (valFormattable != null) { this.WriteValue(key, valFormattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture)); return; } this.WriteValue(key, value.ToString()); return; }
public void ToStringIFormattable() { Color c = new Color(); c.A = 11; c.R = 12; c.G = 13; c.B = 14; ColorFormatter.CallCount = 0; IFormattable f = (c as IFormattable); Assert.AreEqual("#0B0C0D0E", f.ToString(null, null), "null,null"); Assert.AreEqual(0, ColorFormatter.CallCount, "CallCount-a"); Assert.AreEqual("#[11][12][13][14]", f.ToString(null, new ColorFormatter()), "null,ColorFormatter"); Assert.AreEqual(4, ColorFormatter.CallCount, "CallCount-b"); Assert.AreEqual("sc#b, c, d, e", f.ToString("x1", null), "x1,null"); Assert.AreEqual(4, ColorFormatter.CallCount, "CallCount-c"); Assert.AreEqual("sc#@# @# @# @", f.ToString(String.Empty, new ColorFormatter()), "Empty,ColorFormatter"); // 4 times for each byte, 3 times for the ',' character Assert.AreEqual(11, ColorFormatter.CallCount, "CallCount-d"); }
public static string Variable(IDictionary context, string contextKey) { int commaIdx = contextKey.IndexOfAny(new[] { ',', ':' }); object value; if (commaIdx != -1) { value = context[contextKey.Substring(0, commaIdx)]; IFormattable formattable = value as IFormattable; if (formattable != null) { value = formattable.ToString(contextKey.Substring(commaIdx + 1), null); } } else { value = context[contextKey]; } return(Convert.ToString(value)); }
// Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(object value) { if (value == null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if (f != null) { WriteLine(f.ToString(null, FormatProvider)); } else { WriteLine(value.ToString()); } } }
/// <summary> /// Formats a value using a given format string (e.g. "n2" to format a number to include two /// decimal places). /// </summary> /// /// <param name="value">The value to format.</param> /// /// <param name="cellFormat">The format string, e.g. "n2"; if <c>null</c>, it's ignored and /// the default conversion to <c>System.String</c> is used.</param> /// static string FormatValue(object value, string cellFormat) { if (value is DBNull) { return(string.Empty); } if (cellFormat == null) { return(value.ToString()); } IFormattable formattable = value as IFormattable; if (value == null) { return(value.ToString()); } else { return(formattable.ToString(cellFormat, null)); } }
protected override bool EvaluateTokenCore(JsonToken token, object?value, int depth) { if (TryGetChildrenAllValid(token, value, depth, out bool allValid)) { if (!allValid) { List <int> invalidIndexes = new List <int>(); int index = 0; foreach (SchemaScope schemaScope in ChildScopes) { if (!schemaScope.IsValid) { invalidIndexes.Add(index); } else { ConditionalContext.TrackEvaluatedSchema(schemaScope.Schema); } index++; } IFormattable message = $"JSON does not match all schemas from 'allOf'. Invalid schema indexes: {StringHelpers.Join(", ", invalidIndexes)}."; RaiseError(message, ErrorType.AllOf, ParentSchemaScope.Schema, null, ConditionalContext.Errors); } else { for (int i = 0; i < ChildScopes.Count; i++) { ConditionalContext.TrackEvaluatedSchema(ChildScopes[i].Schema); } } } else { RaiseCircularDependencyError(ErrorType.AllOf); } return(true); }
public virtual string _0001() { //Discarded unreachable code: IL_0002 //IL_0003: Incompatible stack heights: 0 vs 1 WatcherComposer watcherComposer = LoginComposer(); switch (watcherComposer) { case WatcherComposer.None: case WatcherComposer.Null: case WatcherComposer.EndArray: return(null); case WatcherComposer.String: return((string)this._0001()); default: if (RulesClientBridge.StartIssuer(watcherComposer)) { object obj = this._0001(); if (obj != null) { IFormattable formattable = obj as IFormattable; string text; if (formattable != null) { text = formattable.ToString(null, this._0001()); } else { Uri uri = obj as Uri; text = (((object)uri != null) ? uri.OriginalString : obj.ToString()); } CancelError(WatcherComposer.String, text, isstate: false); return(text); } } throw ContextError.CheckComposer(this, "Error reading string. Unexpected token: {0}.".ListReader(CultureInfo.InvariantCulture, watcherComposer)); } }
/// <summary> /// Gets culture formatted text representing the property's value</summary> /// <param name="owner">Object whose property text is obtained</param> /// <param name="descriptor">Property descriptor</param> /// <returns>Culture formatted text representing the property's value</returns> public static string GetPropertyText(object owner, PropertyDescriptor descriptor) { string result = string.Empty; // With reflected child property descriptors it is possible to get descriptors // that are supposed to operate on a referenced child rather than the object itself // Using a PropertyDescriptor on an object type it's not designed for often // leads to an exception, which this check safeguards against. if (owner != null && !owner.Is <ICustomTypeDescriptor>() && !descriptor.ComponentType.IsAssignableFrom(owner.GetType())) { return(result); } object value = descriptor.GetValue(owner); if (value != null) { TypeConverter converter = descriptor.Converter; if (converter != null && converter.CanConvertTo(typeof(string))) { result = converter.ConvertTo(value, typeof(string)) as string; } if (string.IsNullOrEmpty(result)) { IFormattable formattable = value as IFormattable; if (formattable != null) { result = formattable.ToString(null, CultureInfo.CurrentUICulture); } else { result = value.ToString(); } } } return(result); }
protected override bool EvaluateTokenCore(JsonToken token, object value, int depth) { if (!GetChildrenAllValid(token, value, depth)) { List <int> invalidIndexes = new List <int>(); int index = 0; foreach (SchemaScope schemaScope in ChildScopes) { if (!schemaScope.IsValid) { invalidIndexes.Add(index); } index++; } IFormattable message = $"JSON does not match all schemas from 'allOf'. Invalid schema indexes: {StringHelpers.Join(", ", invalidIndexes)}."; RaiseError(message, ErrorType.AllOf, ParentSchemaScope.Schema, null, ConditionalContext.Errors); } return(true); }
/// <summary> /// Helper function to retrieve the value of a property on a given object. /// </summary> /// <typeparam name="TSource">The type of the source object whose properties are to be enumerated.</typeparam> /// <typeparam name="TReturn">The type of the property being retrieved.</typeparam> /// <param name="source">The source object whose properties are to be enumerated.</param> /// <param name="propertyName">The name of the property on the source object for which to return the value.</param> /// <returns>The value of the property of interest.</returns> private static TReturn GetProperty <TSource, TReturn>(TSource source, string propertyName) { object Result = null; if (String.IsNullOrEmpty(propertyName) == false) { Type SourceType = typeof(TSource); DefaultFormatStringAttribute SourceFormatAttribute = null; // Get the PropertyInfo for the property of interest on the source type. PropertyInfo SourcePropertyInfo = SourceType.GetProperty(propertyName); // Check for Custom Attributes. foreach (object SourcePropertyAttribute in SourcePropertyInfo.GetCustomAttributes(false)) { if (SourcePropertyAttribute is DefaultFormatStringAttribute) { // The property has been marked with a Default Format String attribute which // should be used to return the value. SourceFormatAttribute = SourcePropertyAttribute as DefaultFormatStringAttribute; } } if (SourceFormatAttribute != null) { // The type of the property of interest on the source type must implement IFormattable // for the DefaultFormatStringAttribute to make any sense. The following will therefore // raise an exception if the type of the property of interest doesn't meet this requirement. IFormattable FormattableValue = (IFormattable)SourcePropertyInfo.GetValue(source, null); Result = FormattableValue.ToString(SourceFormatAttribute.FormatString, null); } else { Result = SourcePropertyInfo.GetValue(source, null); } } return((TReturn)Result); }
protected virtual void GenerateDefaultAttribute(CodeMemberField internalField, CodeTypeMember externalField, TypeData typeData, object defaultValue) { if (typeData.Type == null) { // It must be an enumeration defined in the schema. if (typeData.SchemaType != SchemaTypes.Enum) { throw new InvalidOperationException("Type " + typeData.TypeName + " not supported"); } IFormattable defaultValueFormattable = defaultValue as IFormattable; CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(GetDomType(typeData, false)), defaultValueFormattable != null ? defaultValueFormattable.ToString(null, CultureInfo.InvariantCulture) : defaultValue.ToString()); CodeAttributeArgument arg = new CodeAttributeArgument(fref); AddCustomAttribute(externalField, "System.ComponentModel.DefaultValue", arg); //internalField.InitExpression = fref; } else { AddCustomAttribute(externalField, "System.ComponentModel.DefaultValue", GetArg(defaultValue)); //internalField.InitExpression = new CodePrimitiveExpression (defaultValue); } }
protected ValidationError CreateError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path) { ValidationError error = ValidationError.CreateValidationError(message, errorType, schema, null, value, childErrors, lineInfo, path); return error; }
} //Main() /// <summary> /// Overload that uses null for the IFormatProvider. /// </summary> /// <param name="inputData"></param> /// <param name="formatString"></param> public static void PrintFormat(IFormattable inputData, string formatString) { PrintFormat(inputData, formatString, null); }//PrintFormat()
internal override void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { IsValid = false; base.RaiseError(message, errorType, schema, value, childErrors); }
public static byte[] VfpNumericFormating(IFormattable doubleNum, Encoding charEncoding, int fieldLength, int sizeDecimalPart) { int sizeWholePart = fieldLength - (sizeDecimalPart > 0 ? (sizeDecimalPart + 1) : 0); StringBuilder format = new StringBuilder(fieldLength); for (int i = 0; i < sizeWholePart; i++) { format.Append(i + 1 == sizeWholePart ? "0" : "#"); } if (sizeDecimalPart > 0) { format.Append("."); for (int i = 0; i < sizeDecimalPart; i++) { format.Append("0"); } } if (doubleNum is double) return BitConverter.GetBytes((double)doubleNum); else if (doubleNum is int) return BitConverter.GetBytes((int)doubleNum); return new byte[0]; }
public override ValidationError CreateError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { return CreateError(message, errorType, schema, value, childErrors, null, _writer.Path); }
/// <summary> /// Interpolates the string in invariant culture /// /// Note: this is the only method that requires .NET framework 4.6 /// If we ever need to drop to 4.5, we'll just format the string the old way. /// </summary> /// <param name="format"></param> /// <returns></returns> private static string formatInvariant(IFormattable format) { return format.ToString(null, System.Globalization.CultureInfo.InvariantCulture); }
private void SetInvoiceInfo(string invoiceNumber, IFormattable amountSoldInt, float amountPaidInt, float amountPaidRiel, IFormattable amountReturnInt) { lblInvoiceNum.Text = invoiceNumber; lblFinalAmount.Text = Resources.ConstPrefixDollar + amountSoldInt.ToString("N", AppContext.CultureInfo); lblAmountPaid.Text = Resources.ConstPrefixDollar + (amountPaidInt + (amountPaidRiel * _exchangeRate)).ToString("N", AppContext.CultureInfo); lblAmountReturn.Text = Resources.ConstPrefixDollar + amountReturnInt.ToString("N", AppContext.CultureInfo); }
internal static ValidationError CreateValidationError(IFormattable message, ErrorType errorType, JSchema schema, Uri schemaId, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path) { ValidationError error = new ValidationError(); error._formattable = message; error.ErrorType = errorType; error.Path = path; if (lineInfo != null) { error.LineNumber = lineInfo.LineNumber; error.LinePosition = lineInfo.LinePosition; } error.Schema = schema; error.SchemaId = schemaId; error.SchemaBaseUri = schema.BaseUri; error.Value = value; error.ChildErrors = childErrors; return error; }
public int ReferenceType4(IFormattable arg) { return 1; }
}//PrintFormat(IFormattable inputData, string formatString, IFormatProvider provider) /// <summary> /// Gets a format string from the user and calls PrintFormat() with it. /// </summary> /// <param name="inputData"></param> public static void TryUserFormat(IFormattable inputData) { while (true) { Console.Write("\nType a test format or <enter> to continue: "); string UserFormat = Console.ReadLine(); if (UserFormat == null || UserFormat == string.Empty) { Console.WriteLine(); return; }//if else { PrintFormat(inputData, UserFormat); }//else }//while (true) }//TryUserFormat()
}//PrintFormat() /// <summary> /// Outputs the data with the specified format. /// </summary> /// <param name="inputData"></param> /// Data item /// <param name="formatString"></param> /// Format string /// <param name="outFormat"></param> /// Special output format for custom output spacing. /// <param name="provider"></param> /// Custom format provider public static void PrintFormat(IFormattable inputData, string formatString, IFormatProvider provider) { try { if (provider == null) { Console.WriteLine("{0}\t{1}", formatString, inputData.ToString(formatString, provider)); }//if else { string formstr = "{0} in the custom " + formatString + " format is {1:" + formatString + "}"; Console.WriteLine(string.Format(provider, formstr, inputData, inputData)); }//else }//try catch (Exception e) { Console.WriteLine("Exception in PrintFormat(): {0}", e.Message); Console.WriteLine("Data was {0}, Format string was: {1}, Type was {2}", inputData, formatString, inputData.GetType().Name); }//catch }//PrintFormat(IFormattable inputData, string formatString, IFormatProvider provider)
public IsLessThanValidationResult(IFormattable value, IFormattable max, bool isValid, object errorContent) : base(isValid, errorContent) { this.Value = value; this.Max = max; }
public abstract void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors);
public IsGreaterThanValidationResult(IFormattable value, IFormattable min, bool isValid, object errorContent) : base(isValid, errorContent) { this.Value = value; this.Min = min; }
public int[] GetChangedBugsIds(IFormattable date) { var myDtfi = new CultureInfo("en-US", false).DateTimeFormat; var url = String.Format("cmd=get_bug_ids&name={0}&date={1}", HttpUtility.UrlEncode(_profile.SavedSearches), date.ToString("dd-MMM-yyyy HH:mm:ss", myDtfi)); var content = UploadDataToBugzilla(url); content = ParseResponse(content); try { var ids = content.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return ids.Select(Int32.Parse).ToArray(); } catch (Exception) { throw new InvalidOperationException(string.Format("Unable to take bug ids from Bugzilla. Bugzilla returned an error: {0}", content)); } }
public static String Invariant(IFormattable formattable) => formattable.ToStringInvariant(null);
/// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="f">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="f"/>.</returns> public string ToString(IFormattable f, string format) { return f.ToString(format, _info); }
/// <summary>Formats the object using the formatting arguments.</summary> /// <param name="obj"> /// The IFormattable object to get the formatted string representation from. /// </param> /// <returns> /// A formatted string representing the object. /// </returns> public string ToString(IFormattable obj) { if (obj == null) { return null; } return obj.ToString(this.Format, this.FormatProvider ?? CultureInfo.CurrentCulture); }
/// <summary> /// Test that the "G" format gives the same result as ToString(). /// </summary> /// <param name="obj">The object to test</param> private static void VerifyIFormattableGeneralEqualsToString(IFormattable obj) { Assert.AreEqual(obj.ToString(), obj.ToString("G", CultureInfo.InvariantCulture)); Assert.AreEqual(obj.ToString(), String.Format("{0}", obj)); }
private static string WithCulture(IFormattable f, string cultureName) { return f.ToString(null, System.Globalization.CultureInfo.CreateSpecificCulture(cultureName)); }
public override void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors) { _hasErrors = true; Validator.RaiseError(message, errorType, schema, value, childErrors); }
private static string ToString(IFormattable value, string format) { if (format.IsNullOrEmpty()) return value.ToString(); // return value.ToString(null, CultureInfo.InvariantCulture); // w/o format Money is formatted dirrerently... CultureInfo cultureInfo; return TryGetCultureInfo(format, out cultureInfo) ? value.ToString(null, cultureInfo) : value.ToString(format, CultureInfo.InvariantCulture); }
private void SetPurchasedInfo(IFormattable totalQtyPurchased) { lblPurchaseInfo.Text = Resources.ConstPurchaseInfoPrefix + totalQtyPurchased.ToString("N0", AppContext.CultureInfo); }
public int Value_ReferenceType4(IFormattable arg) { return 2; }