4,632,875 members and growing!   9,603 now online.
Email Password Password problem?
All Topics, C#, .NET >> C# Libraries >> Unedited Reader Contributions  (Beginner)

A simple TextBox TraceListener
By Adam Crawford.

A tracelistener class to allow you to view the results of the trace in your Windows UI test harness
C# (C# 2.0)
Windows, .NET (.NET 1.0, .NET 1.1, .NET 2.0)
Win32, VS
Dev
Posted: 24 Oct 2007
Views: 654
Note: This is an unedited reader contribution  
Announcements


Search    
Advanced Search
Sitemap
PrintBroken Article?Bookmark Discuss Send to a friend
3 votes for this article.
Popularity: 1.91. Rating: 4 out of 5.
Screenshot - TextBoxTraceListener.jpg

Introduction

This is a simple custom TraceListener class to allow text boxes to show the result of the trace in a multi-threaded application.

Background

I was writing a test harness for one of my services and figured someone would have had to of published a TextBoxTraceListener class to save me five minutes, but unfortunately Google came up short. The only examples I could see weren't threadsafe and would have needed all the code to be executed on the Windows UI thread - not exactly great when you're running a service test harness. So I figured I'd throw one together and put it out there for re-use. It's a very simple class really just to save people a bit of time.

Using the code

Just add the TextBoxTraceListener class to your code, then create an instance of the listener (passing in the textbox you want to output the trace to in the constructor), then add your trace listener to Trace or Debug. The sample test harness should give you a pretty good idea of what to do, but it's probably going to look something like this (where txtDisplayTrace is a text box on the form):
    public partial class Form1 : Form
    {
        TextBoxTraceListener _textBoxListener;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _textBoxListener = new TextBoxTraceListener(txtDisplayTrace);
            Trace.Listeners.Add(_textBoxListener);
        }
    } 

Points of Interest

I very rarely get to do anything that requires a UI so I frequently forget that you can't access controls from a different thread until I compile and get an error (then the memory of previous pains comes flooding back). Of course to solve this issue, all you have to do is call Invoke on the control in question and pass it a delegate to the method you want to execute, which is pretty much all the TextBoxTraceListener does; extend the tracelistener class and invoke the update method (the code file has comments, which I've stripped from here)

public class TextBoxTraceListener : TraceListener
{
    private TextBox _target;
    private StringSendDelegate _invokeWrite;

    public TextBoxTraceListener(TextBox target)
    {
        _target = target;
        _invokeWrite = new StringSendDelegate(SendString);
    }
    
    public override void Write(string message)
    {
        _target.Invoke(_invokeWrite, new object[] { message });
    }

    public override void WriteLine(string message)
    {
        _target.Invoke(_invokeWrite, new object[] { message + Environment.NewLine });
    }

    private delegate void StringSendDelegate(string message);
    private void SendString(string message)
    {
        // No need to lock text box as this function will only ever be executed from the UI thread
        _target.Text += message;
    }
}

Hopefully someone out there will find it useful for saving 5 minutes of coding.

About Adam Crawford


After getting a BEng in Comp. Sci at York Uni, I spent 2 years working as a consultant for Accenture but realised it wasn't for me as it wasn't hand on technical enough and the only challenge was completing a ridiculous amount of work in a very short space of time. I'm now working as an ASP.NET / C# integration developer in a CTI firm in Reading.

MCTS (.Net Framework 2 Web Applications) - working towards making that an MCPD

Click here to view Adam Crawford's online profile.


Other popular C# Libraries articles:




[Top] Sign in to vote for this article:     PoorExcellent  
Note: You must Sign in to post to this message board.
Hint: For a faster board use IE 4+ or Mozilla, choose 'Message View' from the View dropdown and hit 'Set Options'.
FAQ Message score threshold    Search comments  
 View   Per page  
 Total Messages for this article: 0 (Refresh) 
Subject 
Author 
Date 
-- No entries --

General comment    News / Info    Question    Answer    Joke / Game    Admin message


Updated: 24 Oct 2007 Article content copyright Adam Crawford, 2007
everything else Copyright © CodeProject, 1999-2007.
Web18 | Advertise on The Code Project | Privacy

The Ultimate ToolboxASP AllianceDeveloper FusionDevelopersdexDevGuruProgrammers HeavenPlanet Source CodeTek-Tips Forums