Skip to content

Instantly share code, notes, and snippets.

@remcoros
Created February 1, 2012 15:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remcoros/1717660 to your computer and use it in GitHub Desktop.
Save remcoros/1717660 to your computer and use it in GitHub Desktop.
Clay Walker
// ClayWalker
public class ClayWalker
{
private readonly Func<int, string, object, object> _memberfound;
public ClayWalker(Func<int, string, object, object> memberfound)
{
_memberfound = memberfound;
}
public void Walk(int depth, object obj)
{
var clay = (IClayBehaviorProvider)obj;
try
{
var e = ((dynamic)obj).GetEnumerator();
int i = 0;
if (e != null && e.MoveNext())
{
depth++;
do
{
_memberfound(depth, i.ToString(), e.Current);
i++;
Walk(depth + 1, e.Current);
} while (e.MoveNext());
}
}
catch (RuntimeBinderException ex)
{
}
var members = new Dictionary<string, object>();
clay.Behavior.GetMembers(() => null, clay, members);
foreach (var key in members.Keys.Where(key => !key.StartsWith("_")))
{
_memberfound(depth, key, members[key]);
var child = members[key] as IClayBehaviorProvider;
if (child != null)
Walk(++depth, members[key]);
}
}
public void Walk(object obj)
{
Walk(0, obj);
}
}
// Helper
private static string GetClayStructure(object obj)
{
var sb = new StringBuilder();
var w = new IndentedTextWriter(new StringWriter(sb), " ");
var walker = new ClayWalker((depth, key, value) =>
{
w.Indent = depth;
w.WriteLine(string.Format("{0}:{1}", key, value));
return null;
});
walker.Walk(obj);
return sb.ToString();
}
// Example Clay:
New.Page(
Test: "fff",
Foo: "Bar",
ContentItems: New.Array(
New.ContentItem(
Id: "1"
),
New.ContentItem(
Id: "2",
HeadContent: New.ContentItem(
Id: "2_1"
)
)
)
);
// Output:
ShapeName:Page
Test:fff
Foo:Bar
ContentItems:ClaySharp.Clay
0:ClaySharp.Clay
ShapeName:ContentItem
Id:1
1:ClaySharp.Clay
ShapeName:ContentItem
Id:2
HeadContent:ClaySharp.Clay
ShapeName:ContentItem
Id:2_1
@nogginbox
Copy link

I'm trying to use this, but I'm getting the error for line 14 of your code:

Unable to cast object of type 'IShapeProxyf45f9b479a004444a7168974c9e2dbfd' to type 'ClaySharp.IClayBehaviorProvider'.

Any idea what I'm doing wrong?

I'm calling GetClayStructure(Model) in Layout.cshtml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment