2011年2月10日木曜日

お手軽Inspector

@using System.Text
@using System.Collections
@using System.Reflection
@functions {
    public static string Inspector(object model)
    {
        if (model == null)
            return "";
        var type = model.GetType();
        if (type == typeof(string))
            return model.ToString();
        
        var properties = type.GetProperties();

        var inspect = new StringBuilder();
        inspect.Append("{");

        var vals = new List<string>();
        foreach (PropertyInfo property in properties)
        {
            var val = property.GetValue(model, null);
            var name = property.Name;

            if (val != null)
            {
                if ((property.PropertyType.IsArray || val as IEnumerable != null) && property.PropertyType != typeof(string))
                {
                    // ちょっとズル。
                    val = "["+string.Join(",", (from object v in (IEnumerable)val where v != null select Inspector(v)).ToArray())+"]";
                }
                else if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
                {
                    var descendants = Inspector(val);
                    if (descendants != null)
                        val = descendants;
                }
                else
                {
                    val = val.ToString();
                }

                val = string.Format("{0}:{1}", name, val);
            }
            vals.Add(val.ToString());
        }
        inspect.Append(string.Join(",", vals));
        inspect.Append("}");

        return inspect.ToString();
    }
}
@{
    var model = new
    {
        Name = "オレがルールだ!",
        FavoriteSong = "明日があるさ",
        List = new List<string> { "First", "Second", "Third" },
        Sub = new { Name = "昔ね", Description = "そんなブログもあったよね" }
    };
}
@Html.Raw(Inspector(model))

inspector

http://razordo.it/now/wxvs

WebMatrixにはデバッガがないのでデバッグやテストの時に不便ですよね。なので、お手軽Inspector。

確か、NuGetにちゃんとしたのがあった気がするけど気にしない。最初はTypeDescriptorでPropertyDescriptorで取得しようとしたけど、Medium Trustでは駄目だったからReflectionで。

試してみたい場合はもちろんRazor Do It。

今日は違うことする予定だったんだけど、なんかどうしても試したくなったっす。やむなしっす。

dotnetConf2015 Japan

https://github.com/takepara/MvcVpl ↑こちらにいろいろ置いときました。 参加してくださった方々の温かい対応に感謝感謝です。