using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI; using System.Web; using System.IO; namespace StringLib { public static class JonFormatter { public static string JonFormat(this string format, object source) { if (format == null) { throw new ArgumentNullException("format"); } StringBuilder sb = new StringBuilder(format.Length * 2); char[] a = format.ToCharArray(); int last = a.Length - 1; for (int i = 0; i <= last; i++) { switch(a[i]) { case '{': if (i < last && a[i + 1] != '{') { i++; int j = i; int b = -1; while (i < last && a[i] != '}') { i++; if (a[i] == ':') { b = i; } } if (i == last && a[i] != '}') { throw new FormatException(); } try { if (b < 0) { sb.Append(DataBinder.Eval(source, format.Substring(j, i - j))); } else { sb.Append(String.Format("{0" + format.Substring(b, i - (b - 1)), DataBinder.Eval(source, format.Substring(j, b - j)))); } } catch (HttpException) { throw new FormatException(); } } else { if (i == last) { throw new FormatException(); } sb.Append('{'); i++; } break; case '}': if (i == last || a[i + 1] != '}') { throw new FormatException(); } else { sb.Append('}'); i++; } break; default: sb.Append(a[i]); break; } } return sb.ToString(); } } }