Dumping Properties of an Object

Sometimes I see myself in weird situations, having to debug applications in test environments, but for some reason I'm not able to use Visual Studio. Not going to specific details about my environments here. However, it's possible that someone out there have a similar issue. For these cases, I use Reflection to dump the contents of my objects into a string and save it in a text file to analyze later.

This is the "Dump" method:

public static string Dump(Object obj) {
    string dump = string.Empty;
    try {
        Dictionary<string, string> dictionary =
            new Dictionary<string, string>();
        Type type = obj.GetType();
        System.Reflection.PropertyInfo[] propInfo = type.GetProperties();
        for (int i = 0; i < propInfo.Length; i++) {
            System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo)propInfo.GetValue(i);
            dictionary.Add(pi.Name,
                (null == pi.GetValue(obj, new object[] { })) ?
                "null" : pi.GetValue(obj, new object[] { }).ToString());
        }
        foreach (System.Collections.Generic.KeyValuePair<string, string> pair in dictionary) {
            dump += string.Format("{0}\t{1}\n", pair.Key, pair.Value);
        }
    }
    catch (Exception ex) {
        // use a proper log instead of a text file..
        System.IO.File.AppendAllText(@"C:\myapplicationname.dump.exception.txt",
            "--------------------------------------\n"+
            "Exception:\n\tSource: " + ex.Source +
            "\n\tMessage: \n" + ex.Message +
            "\n\tStack: \n" + ex.StackTrace +
            "\n------------------------------------");
    }
    return dump;
}
 
Sometimes I use this technique to debug CRM Plug-ins. I hope it's useful for you guys.
Here's a Sample Console Project using the Dump method.

Published Monday, November 17, 2008 12:22 PM by tsantos
Filed under: , ,

Comments

# re: Dumping Properties of an Object

Friday, March 26, 2010 5:13 AM by Airlia

Badly need your help. Please post your favorite sites. Help me! Can not find sites on the: Deramtology medications proventil. I found only this - <a href="genericproventil.info/">french proventil bedroom</a>. There are some acceptable outcome results of the way sundry, proventil. Proventil, this represents limited lines starting what convenience devices gathered from internet this here few giveaway. Waiting for a reply :-(, Airlia from Moldova.

Leave a Comment

(required) 
(required) 
(optional)
(required)