private static string FormatWithAnonymousObject(string message, object model)
{
var type = model.GetType();
if(type == typeof(string))
return string.Format(message, model);
var placeHolders = Regex.Matches(message, "{.*?}").Cast<Match>().Select(m => m.Value).ToList();
if(!placeHolders.Any())
return message;
var placeholderMap = new Dictionary<string, object>();
var properties = type.GetProperties();
foreach (var placeHolder in placeHolders)
{
var propertyInfo = properties.FirstOrDefault(p => p.Name == placeHolder.Trim('{', '}'));
// property found - extract value and add to the map
var val = propertyInfo?.GetValue(model);
if(val != null)
placeholderMap.Add(placeHolder, val);
}
return placeholderMap.Aggregate(message, (current, pair) => current.Replace(pair.Key, pair.Value.ToString()));
}