// -----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// -----------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.WebserverBasics
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
///
/// Remembers the most recent trace events observed and exposes them as
/// a chunk of displayable text.
///
public class RecentEventBufferTraceListener : TraceListener
{
private const int DefaultMaximumLines = 10;
private readonly StringBuilder traceLineBuilder = new StringBuilder();
private readonly Queue entries;
private readonly int maximumLines;
///
/// Initializes a new instance of the class.
///
///
/// Remembers the default number of trace lines.
///
public RecentEventBufferTraceListener()
: this(DefaultMaximumLines)
{
}
///
/// Initializes a new instance of the class.
///
///
/// Maximum number of trace lines to remember.
///
public RecentEventBufferTraceListener(int maximumLines)
{
this.maximumLines = maximumLines;
this.entries = new Queue(maximumLines);
}
public event EventHandler RecentEventBufferChanged;
///
/// Displayable string representing buffer of recent trace events seen.
///
public string RecentEventBuffer { get; private set; }
///
/// Remembers the specified message as the latest message seen.
///
///
/// Message to remember.
///
public override void Write(string message)
{
this.traceLineBuilder.Append(message);
}
///
/// Remembers the specified message, followed by a line terminator, as the latest
/// message seen.
///
///
/// Message to remember.
///
public override void WriteLine(string message)
{
this.traceLineBuilder.Append(message);
this.traceLineBuilder.Append("\n");
this.QueueMessage(this.traceLineBuilder.ToString());
this.traceLineBuilder.Clear();
}
///
/// Remembers the specified message as the latest message seen.
///
///
/// Message to remember.
///
private void QueueMessage(string message)
{
this.entries.Enqueue(message);
if (this.entries.Count > this.maximumLines)
{
this.entries.Dequeue();
}
var builder = new StringBuilder();
foreach (var entry in this.entries)
{
builder.Append(entry);
}
this.RecentEventBuffer = builder.ToString();
if (this.RecentEventBufferChanged != null)
{
this.RecentEventBufferChanged(this, EventArgs.Empty);
}
}
}
}