:::: MENU ::::

Tuesday, November 18, 2008

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;
}