How to build the debugger into the GUI

Mar 27, 2013 at 3:19 PM
Hi,

I want to use your debug-methods to create a logging-Feature in my program. I want to get the FTP log into a Listbox. The user shall enable the logging via a checkbox. If any error occurs the user shall enable logging and can provide me with the log. This makes debugging my code easier in the future.

Best regards
Coordinator
Mar 27, 2013 at 3:31 PM
Edited Mar 27, 2013 at 3:33 PM
Create a class that extends TraceListener, build System.Net.FtpClient #define DEBUG, add an instance of your tracelistener to the System.Diagnostics.Debug.TraceListeners collection. Example:
using System.Diagnostics;
using System.Windows.Forms;

public class FtpLogger : TraceListener {
    private TextBox m_textbox = null;

    private void AddText(string text) {
        if(m_textbox != null) {
            m_textbox.Text += text;
            // scroll to end of text buffer
            m_textbox.SelectionStart = m_textbox.Text.Length;
            m_textbox.ScrollToCaret();
        }
    }

    public override void Write(string message) {
        AddText(message);
    }

    public override void WriteLine(string message) {
        AddText(message + Environment.NewLine);
    }

    public FtpLogger(TextBox text) {
        m_textbox = text;

        if(m_textbox != null) {
            // keep the user from modifying the contents
            // but still allow them to select and copy the log
            m_textbox.ReadOnly = true;
        }
    }
}

...

Debug.TraceListeners.Add(new FtpLogger(theTextBox));
Coordinator
Mar 27, 2013 at 3:38 PM
Edited Mar 27, 2013 at 3:39 PM
If you are using threaded code or the Begin* methods take care to use Invoke(), BeginInvoke() in your trace listener when updating the textbox or whatever control you decide to use. I.e.,
m_textbox.Invoke(new MethodInvoker(delegate() {
   m_textbox.Text += text;
   // scroll to end of text buffer
   m_textbox.SelectionStart = m_textbox.Text.Length;
   m_textbox.ScrollToCaret();
}));
Coordinator
Mar 27, 2013 at 3:41 PM
Here are some examples included with the project:

Examples\Debug.cs
Mar 27, 2013 at 3:48 PM
OK thank you, I translated the class into VB.Net. Where do i add the TraceListener? Just at the beginning of the programm?
Coordinator
Mar 27, 2013 at 3:50 PM
I would add it in the Load event of your form so that it doesn't try to access the textBox until it's been created and is ready to be used. In addition, I would remove the trace listener from Debug.TraceListeners in the FormClosing event, before the textbox has been destroyed.