Created
January 16, 2009 10:02
-
-
Save atifaziz/47888 to your computer and use it in GitHub Desktop.
Updated HenriFormatter from Named Formats Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://haacked.com/archive/2009/01/14/named-formats-redux.aspx#70485 | |
using System; | |
using System.Text; | |
using System.Web; | |
using System.Web.UI; | |
namespace StringLib | |
{ | |
public static class HenriFormatter | |
{ | |
public static string HenriFormat(this string format, object source) | |
{ | |
if (format == null) | |
throw new ArgumentNullException("format"); | |
var result = new StringBuilder(format.Length * 2); | |
var expression = new StringBuilder(); | |
var e = format.GetEnumerator(); | |
while (e.MoveNext()) | |
{ | |
var ch = e.Current; | |
if (ch == '{') | |
{ | |
while (true) | |
{ | |
if (!e.MoveNext()) | |
throw new FormatException(); | |
ch = e.Current; | |
if (ch == '}') | |
{ | |
result.Append(OutExpression(source, expression.ToString())); | |
expression.Length = 0; | |
break; | |
} | |
if (ch == '{') | |
{ | |
result.Append(ch); | |
break; | |
} | |
expression.Append(ch); | |
} | |
} | |
else if (ch == '}') | |
{ | |
if (!e.MoveNext() || e.Current != '}') | |
throw new FormatException(); | |
result.Append('}'); | |
} | |
else | |
{ | |
result.Append(ch); | |
} | |
} | |
return result.ToString(); | |
} | |
private static string OutExpression(object source, string expression) | |
{ | |
string format = "{0}"; | |
int colonIndex = expression.IndexOf(':'); | |
if (colonIndex > 0) | |
{ | |
format = "{0:" + expression.Substring(colonIndex + 1) + "}"; | |
expression = expression.Substring(0, colonIndex); | |
} | |
try | |
{ | |
return DataBinder.Eval(source, expression, format) ?? string.Empty; | |
} | |
catch (HttpException) | |
{ | |
throw new FormatException(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment