Skip to content

Instantly share code, notes, and snippets.

@TiagoSoczek
Forked from dotnetchris/HenriFormatter.cs
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save TiagoSoczek/9898244 to your computer and use it in GitHub Desktop.

Select an option

Save TiagoSoczek/9898244 to your computer and use it in GitHub Desktop.
namespace Project.Tests
{
using Api.Extensions.NamedFormatter;
using Xunit;
public class NamedFormatterTestCase
{
[Fact]
public void Simple()
{
var formatted = "test {user}".NamedFormat(new { user = "tiago" });
Assert.Equal("test tiago", formatted);
}
[Fact]
public void Complex()
{
var user = new UserDummy { UserName = "tiago" };
var formatted = "test {user.UserName}".NamedFormat(new { user });
Assert.Equal("test tiago", formatted);
}
[Fact]
public void Escaped()
{
var formatted = "test {{user}}".NamedFormat(new { user = "tiago" });
Assert.Equal("test {user}", formatted);
}
}
public class UserDummy
{
public string UserName { get; set; }
}
}
// http://haacked.com/archive/2009/01/14/named-formats-redux.aspx#70485
namespace Project.Extensions.NamedFormatter
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Routing;
using System.Web.UI;
public static class NamedFormatter
{
public static string NamedFormat(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
{
if (string.IsNullOrEmpty(format))
{
if (source is RouteData)
{
source = ((RouteData)source).Values;
}
var dict = source as IDictionary<string, object>;
return dict != null ? dict[expression].ToString() : (DataBinder.Eval(source, expression) ?? string.Empty).ToString();
}
return DataBinder.Eval(source, expression, format);
}
catch (HttpException)
{
throw new FormatException();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment