Friday, December 7, 2007

Trace Your Code Effectively !

Here is quick and nice trick to trace your code and append the values in the Textbox. For this we have to design a class which inherits from 'TraceListener' Class then we must override the 'Write' and 'WriteLine' method to give it our own logic. So, here it is:

Public Class TraceLogSupport
......Inherits TraceListener

......Private _Targettextbox As RichTextBox
......Private _Targetfrm As Form

......Public Sub New()
............MyBase.New()
............'default constructor
......End Sub

......Public Sub New(ByVal txtbox As RichTextBox, ByVal frm As Form)
............MyBase.New()

......If txtbox IsNot Nothing Then

............_Targettextbox = txtbox

......Else

............MyBase.Dispose()
............Throw New ArgumentNullException("Must specify which Textbox to append text to.")

......End If

......_Targetfrm = frm

......End Sub

......Delegate Sub SetTextCallBack(ByVal text As String)

......Public Overloads Overrides Sub Write(ByVal message As String)
............SetText(message)
......End Sub

......Public Overloads Overrides Sub WriteLine(ByVal message As String)
............SetText(message + Environment.NewLine)
......End Sub

......'Just to make it thread safe.
......Sub SetText(ByVal txt As String)
............If Me._Targettextbox.InvokeRequired Then
..................Dim stcallback As New SetTextCallBack(AddressOf SetText)
.................._Targetfrm.Invoke(stcallback, New Object() {txt})
......Else
..................Me._Targettextbox.AppendText(txt)
......End If

......End Sub

End Class

Now just instantiate the object of this class and add it to Trace's or Debug's listener's collection (Both share the same Listener's collection). Trace and Debug classes can be accessed from anywhere in your code in this way you can easily display the result of your code execution. This is just to make your execution live !

No comments: