using System.Diagnostics;
using System.Threading;
using Telerik.WinControls.UI;
using System;

public class OpenAccessTracer : TraceListener
{
  int id;
  int count;
  RadTextBox textBox;
  RadLabel label;
  Thread myThread;

  public OpenAccessTracer(RadTextBox textBox)
    : base("OpenAccess")
  {

    myThread = Thread.CurrentThread;

    Telerik.OpenAccess.Diagnostics.TraceAdapter.Instance.Level = "4";
    id = Telerik.OpenAccess.Diagnostics.TraceAdapter.Instance.Listeners.Add(this);
    this.textBox = textBox;

    count = 0;
  }

  public OpenAccessTracer(RadTextBox textBox, RadLabel label)
    : base("OpenAccess")
  {

    myThread = Thread.CurrentThread;

    Telerik.OpenAccess.Diagnostics.TraceAdapter.Instance.Level = "4";
    id = Telerik.OpenAccess.Diagnostics.TraceAdapter.Instance.Listeners.Add(this);
    this.textBox = textBox;
    this.label = label;
    count = 0;
  }

  protected override void Dispose(bool disposing)
  {
    this.textBox.Text += count.ToString() + " queries executed.";
    Telerik.OpenAccess.Diagnostics.TraceAdapter.Instance.Listeners.RemoveAt(id);
    base.Dispose(disposing);
  }

  public void Reset()
  {
    textBox.Text = String.Empty;
    label.Text = String.Empty;
    count = 0;
  }

  public override void Write(string message)
  {

  }

  public override void WriteLine(string message)
  {
    if (!myThread.Equals(Thread.CurrentThread))
      return;

    if (label != null)
    {
      label.Text = count.ToString() + " queries executed.";
    }

    if (message.StartsWith("driver.stat.execQuery"))
    {
      count++;
      textBox.Text += string.Format("{0}: {1}\r\n", count.ToString(),
        message.ToString().Substring(32).Trim());
    }
  }

}