I'm working with a 3rd-party library that does some machine-specific
calculations. It's called through COM interop, and takes a ton
of parameters. When something doesn't come out right, it's nice to be
able to quickly view what's being send in and returned without spending
an excessive amount of time in the debugger... so I use this
quick-and-dirty little wrapper to dump them to the output window:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.InteropServices;
using System.Diagnostics;
public class DebugTraceProxy
: RealProxy
{
readonly MarshalByRefObject target;
public static T NewObject<T>()
{
return (T)(new DebugTraceProxy(typeof(T)).GetTransparentProxy());
}
private DebugTraceProxy(Type t)
: base(t)
{
target = (MarshalByRefObject)Activator.CreateInstance(t);
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage call = msg as IMethodCallMessage;
Debug.WriteLine(call.MethodName + ":");
for (int i = 0; i < call.InArgCount; ++i)
{
string name = call.GetInArgName(i);
object arg = call.GetInArg(i);
Debug.WriteLine(" " + name + ": " + DumpOb(arg));
}
IMethodReturnMessage ret = RemotingServices.ExecuteMessage(target, (IMethodCallMessage)msg);
Debug.WriteLine("Returned:");
for (int i = 0; i < ret.OutArgCount; ++i)
{
string name = ret.GetOutArgName(i);
object arg = ret.GetOutArg(i);
Debug.WriteLine(" " + name + ": " + DumpOb(arg));
}
return ret;
}
private string DumpOb(object ob)
{
Type t = ob.GetType();
if (t.IsPrimitive || t == typeof(string))
return ob.ToString();
string obDesc = "";
FieldInfo[] infos = t.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
if (infos.Length == 0)
return ob.ToString();
foreach (FieldInfo field in infos)
{
if (obDesc != "")
obDesc += ", ";
obDesc += field.Name + ": " + field.GetValue(ob).ToString();
}
return obDesc;
}
}
To use it, I create the object like so:
CrazyOb myCrazyOb = DebugTraceProxy.NewObject<crazyob>();
Reflection... handy.

