Thursday, January 02, 2014

Dynamic Object with custom object graph and loose rule option

Recently, I need this custom dynamic object to parse my razor model which require a loose type and object graph.

such as
Model.ConnectionString.Test
Model.ConnectionString
Model.ConnectionString.Test2

if there is no value, it will give empty string instead of error when calling RazorEngine.Parse()

Here is the dynamic object, use it when you really need it.



public class DynamicModel : DynamicObject
{
private readonly bool _isStrictGet;
public IDictionary<string, object> _dict;
public DynamicModel(string objectName = null, IDictionary<string, object> dict = null, bool isStrictGet = false)
{
ObjectName = objectName;
_dict = dict ?? new Dictionary<string, object>();
_isStrictGet = isStrictGet;
}
#region <<Override method>>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_dict.ContainsKey(binder.Name))
{
result = _dict[binder.Name];
return true;
}
//if it can't find any keys
if (_isStrictGet)
{
//if you need to be
result = null;
return false;
}
//to make this to return gracefully you can set this to true so that it will return empty string.
result = new DynamicModel("");
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Add(binder.Name, value);
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _dict.Keys;
}
public override string ToString()
{
return ObjectName ?? base.ToString();
}
#endregion
#region <<helper method>>
public void Add(string key, object value)
{
if (_dict.ContainsKey(key))
{
_dict[key] = value;
}
else
{
_dict.Add(key, value);
}
}
public bool ContainsKey(string key)
{
return _dict.ContainsKey(key);
}
public object GetValue(string key)
{
return _dict.ContainsKey(key) ? _dict[key] : null;
}
#endregion
public string ObjectName { get; set; }
}
view raw DynamicModel hosted with ❤ by GitHub