views:

143

answers:

1

I am trying to create a debugger visualizer that would show control hierarchy for any Control. It's done but I'm getting the exception "Type is not marked as serializable".

How do I overcome that? Control is a .NET Windows Forms framework type, I can't mark it as serializable.

+5  A: 

You'll need to also implement a VisualizerObjectSource to perform custom serialization.

Example:

public class ControlVisualizerObjectSource : VisualizerObjectSource
{
    public override void GetData(object target, Stream outgoingData)
    {
        var writer = new StreamWriter(outgoingData);
        writer.WriteLine(((Control)target).Text);
        writer.Flush();
    }
}
public class ControlVisualizer : DialogDebuggerVisualizer
{
    protected override void Show(
        IDialogVisualizerService windowService,
        IVisualizerObjectProvider objectProvider)
    {
        string text = new StreamReader(objectProvider.GetData()).ReadLine();
    }
    public static void TestShowVisualizer(object objectToVisualize)
    {
        var visualizerHost = new VisualizerDevelopmentHost(
            objectToVisualize,
            typeof(ControlVisualizer),
            typeof(ControlVisualizerObjectSource));
        visualizerHost.ShowVisualizer();
    }
}
class Program
{
    static void Main(string[] args)
    {
        ControlVisualizer.TestShowVisualizer(new Control("Hello World!"));
    }
}

You'll also need to register the visualizer with the appropriated VisualizarObjectSource, which for this example could be something like this:

[assembly: DebuggerVisualizer(
    typeof(ControlVisualizer),
    typeof(ControlVisualizerObjectSource),
    Target = typeof(System.Windows.Forms.Control),
    Description = "Control Visualizer")]
João Angelo