VB.NET•Extend the SpecialListener Class

Listing 1. The SpecialListener class is the base for any custom listener that uses the TraceEntry class. You can extend this class to handle additional types of custom trace entries.

Option Strict On
Option Explicit On 

Imports System

Public MustInherit Class SpecialListener
   Inherits Diagnostics.TraceListener

   Public MustOverride Overloads Sub _
      WriteMessage(ByVal traceEntry As _
      TraceEntry)

   Protected mMessage As String
   Protected Disposed As Boolean
   Const crlf As String = _
      Microsoft.VisualBasic.ControlChars.CrLf
   Private Shared TSLevel As _
      Diagnostics.TraceSwitch = _
      New Diagnostics.TraceSwitch( _
      "ShowDialogIf", "Level Switch")

   Public Function IsDebugBuild( _
      ByVal method As Reflection.MethodBase) _
      As Boolean
      Dim asm As Reflection.Assembly
      Dim atts() As Object
      asm = method.DeclaringType.Assembly

      atts = asm.GetCustomAttributes(False)
      For Each item As Object In atts
         If TypeOf item Is _
            Diagnostics. _
            DebuggableAttribute Then
            Return True
         End If
      Next
   End Function

   Public Overloads Overrides Sub Write( _
      ByVal message As String)
      Me.mMessage &= message
   End Sub

   Public Overloads Overrides Sub Write( _
      ByVal o As Object)
      If TypeOf o Is TraceEntry Then
         Me.Write(CType(o, TraceEntry).Issue)
      Else
         Me.Write(o.ToString)
      End If
   End Sub

   Public Overloads Overrides Sub WriteLine( _
      ByVal o As Object)
      If TypeOf o Is TraceEntry Then
         Me.WriteLine(CType(o, TraceEntry))
      Else
         Me.WriteLine(o.ToString)
      End If
   End Sub

   Public Overridable Overloads Sub WriteLine( _
      ByVal traceEntry As TraceEntry)
      Dim msg As String
      WriteMessage(traceEntry)
      If traceEntry.TraceLevel <= TSLevel.Level _
         Then
         If IsDebugBuild( _
            traceEntry.MethodBase) Then
            msg = GetAssertMessage( _
               traceEntry)
            Windows.Forms.MessageBox.Show(msg, _
      "Assert Failure", _
      Windows.Forms.MessageBoxButtons.OK)
         End If
      End If
   End Sub