Remote TracingBuilding a Custom Trace Listener

Remote Tracing”Building a Custom Trace Listener

One of the nice features of using trace listeners and trace switches is that you can centrally and dynamically control all tracing output from a central location. Taking this a step further, you now have a relatively simple means of improving product support for your applications. Such a step allows you to create your own trace listener class to completely customize the output, as well as the trace target. For example, you may want to remotely monitor the health of an application that was installed externally. The application you wish to monitor may not even be installed on your local network. With a custom trace listener, you now have the means of automatically tracing output from an external application to a server accessible to you. I will go through the building of such a feature using three main components :

  • Custom Trace Listener/Sender ” Trace listener to send trace statements remotely.

  • Trace Receiver ” Server that can receive trace statements from a remote source.

  • Trace Viewer (optional) ” Front end to view remote traces (Figure 2.8).

    Figure 2.8. Remote Trace Viewer: Displays all remote traces coming from a message queue or TCP/IP socket.


Building a Custom Trace Listener

Using the .NET trace listener collection, you can easily employ your own custom listeners to route and format trace output as you see fit. Custom trace listeners are manipulated like any other trace listeners. To create one, you must first derive from the TraceListener abstract class and create your own XXX listener class. The name of the class can be anything but typically it will end with the word listener to keep with the .NET convention. Once created, you can than add this listener to the listener collection, as we did in the previous section. You are required to implement only two methods to guarantee that your custom listener will work with .NET tracing. At a minimum, you must implement both the Write and WriteLine abstract methods. You are not required to overload them; one implementation of each is sufficient. Other elements of the TraceListener parent class may also be overridden, such as the Flush or Close methods, but only the Write and WriteLine methods are actually required for compilation. To create our custom remote trace listener, specify something like the code snippet in Listing 2.13.

Please refer to the previous technology backgrounder in this chapter for details on trace listeners and switches.

Listing 2.13 Our Remote Trace Listener template.
[View full width]
 /// <summary> /// This represents the remote tracing custom trace listener that /// will be added during graphics/ccc.gif application initialization /// and allow all tracing to be sent remotely, the tracing level is /// determined by the graphics/ccc.gif trace switch which is /// accessible via a TraceLevel static data member (Config.cs), to /// send remote traces (if turned on), the client /// must use the following code template: /// /// ///      Trace.WriteLineIf(Config.TraceLevel.TraceVerbose, ///              "starting packet translation..."); /// /// </summary> /// /// <example>Trace.WriteLineIf(Config.TraceLevel.TraceVerbose, ///      starting packet graphics/ccc.gif translation...");</example> /// <remarks> /// To change the trace level you must edit the launching /// applications configuration file as such: /// The name attribute must match the name given to the trace /// extension, e.g. RemoteTraceLevel /// <system.diagnostics> ///            <switches> ///                  <add name="RemoteTraceLevel" value="1" /> ///            </switches> /// </system.diagnostics> /// 0 (off), 1 (error), 2 (warning), 3 (info), OR 4 (verbose) /// </remarks> public class RemoteTraceListener : System.Diagnostics.TraceListener {    /// <summary>    /// Reference to the remote tracing web service    /// </summary>    private RemoteTracerServer oRemoteService = null;    /// <summary>    ///    /// </summary>    public RemoteTracerService RemoteService    {          get { return oRemoteService; }          set { oRemoteService = value; }    }    /// <summary>    ///    /// </summary>    public RemoteTraceListener(string sName)    {          // initializes the remote web service that will receive the // remote traces          RemoteService = new RemoteTracerService();          base.Name = sName;    }    /// <summary>    /// Writes output remotely to the remote trace web service (trace    /// receiver    /// </summary>    /// <param name="sMessage"></param>    public override void Write(string sMessage)    {          RemoteService.RemoteTrace(Dns.GetHostName(), sMessage);    }    /// <summary>    /// same as above    /// </summary>    /// <param name="sMessage"></param>    public override void WriteLine(string sMessage)    {          RemoteService.RemoteTrace(Dns.GetHostName(), sMessage);    } 

You can see that the overridden Write and WriteLine methods simply call RemoteService.RemoteTrace , passing the original trace message. RemoteService, in this case, happens to be a Web service running on another system. This service acts as the trace receiver and just so happens to be implemented as a Web service. Any receiver could have been created, as long as the RemoteTraceListener has access to it. I choose to implement the remote trace receiver as a Web service for simplicity. I could have opened a TCP/IP socket, for example, and could send the message directly to some socket server. How you implement the send or receiver is up to you.

Once your remote trace listener is constructed , you can now add it to your listener collection:

Listing 2.14 Sample routine for constructing and adding your custom listener.
 public static void InitTraceListeners() {       . . .       // for remote tracing       if (Trace.Listeners[TRACE_REMOTE_LISTENER_KEY] == null)             Trace.Listeners.Add(new        RemoteTraceListener(TRACE_REMOTE_LISTENER_KEY); } 

Building a Remote Trace Receiver

Once added to the collection, any direct Trace.Write or Trace.WriteLine calls cause your corresponding methods to be called in RemoteTraceListener. Once called, the RemoteTracerService.RemoteTrace will be called. The RemoteTracerService is implemented as follows :

Listing 2.15 A sample Remote Trace Listener Web Service.
 public class RemoteTracerService : System.Web.Services.WebService {       public RemoteTracerService()       {             InitializeComponent();       }       . . .       /// <summary>       /// Called by external clients to send all remote traces       /// into a centrally supplied web service       /// </summary>       [WebMethod]       public void RemoteTrace(string sSource, string sMessage)       {             EventLog oElog = new EventLog("Application",                   Dns.GetHostName(), "RemoteTracer");             try             {                   // first send it to the trace queue, queue                   // should create itself if it has been deleted                   Messenger oMessenger = new Messenger();                   BusinessMessage oMessage =                         oMessenger.MessageInfo;                   oMessage.MessageText = sMessage;                   // uri of the requesting party, this is the                   // host name                   oMessage.UserId = sSource;                   // must set the message type we are looking                   // for, this looks in the correct queue                   oMessage.MessageType = "trace";                   // send the trace to the queue                   oMessenger.Send(oMessage);                   // next send it a socket stream                   string sRemoteTraceTargetHost = "etier3";                   string sIP = Dns.GetHostByName(sRemoteTraceTargetHost).AddressList[0].ToString();                   int nPort = 8001; // any port will do                   Utilities.SendSocketStream(sIP, nPort, sSource                         + ":" + sMessage);             }             catch (Exception e)             {                   // or socket server was not listening, either                   // way just log it and move on...                 oElog.WriteEntry(BaseException.Format(null, 0,                         "Error Occurred During Remoting: " +                         e.Message, e));             }       } } 

Sending Traces to a Message Queue

Inside the try/catch block, I demonstrate the sending of the trace message to two targets. The first message target is a message queue. The second target is any TCP/IP listening socket server. I've wrapped the message queue interaction in a class called Messenger to help abstract the queuing services I may be using. For this example, the following source shows the main features of the Messenger class. This implementation of the Messenger uses the .NET System.Messaging library to communicate with Microsoft Message Queuing . Sending the trace messages to a queue is completely optional but it provides a quick means of persisting messages while providing an asynchronous delivery mechanism.

Listing 2.16 Sample Business Object to be placed on a queue.
 /// <summary> /// This is message information send/received from a queue /// For example, for FTP file transfers the Data property will /// contain the actual file contents /// </summary> public struct BusinessMessage {       /// <summary>       /// see properties for each data member       /// </summary>       private string sType;       private string sUserId;       . . .       private string sQueueName;       private string sMessageText;       private string sDate;       private string sTime;       /// <summary>       ///   Specifying the type sets the queue name to       ///   send/receive to/from       /// </summary>       public string MessageType       {             get {return sType;}             set             {                   sType = value;                   sQueueName = ".\private$\patterns.net_" +                                     sType.ToLower();             }       }       public string MessageText       {             get {return sMessageText;}             set   {sMessageText = value;}       }       public string Date       {             get {return sDate;}             set   {sDate = value;}       }       public string Time       {             get {return sTime;}             set   {sTime = value;}       }       . . .       public string UserId       {             get {return sUserId;}             set {sUserId = value;}       }       public string QueueName       {             get {return sQueueName;}       } } /// <summary> /// Used for sending asynchronous messages to a durable message /// queue of some kind /// This currently using MSMQ and assumes it is installed, /// eventually this will be implemented /// to use any queuing framework. /// </summary> public class Messenger {       /// <summary>       /// Data member for the main message information to be sent       /// and received.       /// </summary>       private BusinessMessage oMessage;       /// <summary>       /// Property for the message information structure, which       /// is an inner structure       /// </summary>       public BusinessMessage MessageInfo       {             get {return oMessage;}             set {oMessage = value;}       }       /// <summary>       /// Initializes an empty message information structure       /// </summary>       public Messenger()       {             MessageInfo = new BusinessMessage();       }       /// <summary>       /// Sends the providing message info structure to a queue,       /// queuename should be set in the MessageInfo struct       /// This just set the MessageInfo property and delegates to       /// Send()       /// </summary>       /// <param name="oMessage"></param>       public void Send(BusinessMessage oMessage)       {             MessageInfo = oMessage;             Send();       }       /// <summary>       /// Sends the set MessageInfo data to the queue based on       /// the MessageInfo.QueueName property       /// This will be serialized as xml in the message body       /// </summary>       public void Send()       {             try             {                   string sQueuePath = MessageInfo.QueueName;                   if (!MessageQueue.Exists(sQueuePath))                   {                         // queue doesn't exist so create                         MessageQueue.Create(sQueuePath);                   }                   // Init the queue                   MessageQueue oQueue = new                         MessageQueue(sQueuePath);                   // send the message                   oQueue.Send(MessageInfo,                               MessageInfo.MessageType + " - " +                               MessageInfo.Uri);             }             catch (Exception e)             {                   throw new BaseException(this, 0, e.Message, e,                                           false);             }       }       /// <summary>       /// Receives a message based on the MessageInfo.QueueName       /// of the MessageInfo struct passed in.       /// </summary>       /// <param name="oMessage"></param>       public BusinessMessage Receive(BusinessMessage oMessage,                                     int nTimeOut)       {             MessageInfo = oMessage;             return Receive(nTimeOut);       }       /// <summary>       /// Uses the set MessageInfo.QueueName to retrieve a       /// message from the specified queue.       /// If the queue cannot be found or a matching       /// BusinessMessage is not in the queue an exception will       /// be thrown.       /// This is a "polling" action of receiving a message from       /// the queue.       /// </summary>       /// <returns>A BusinessMessage contains body of message       /// deserialized from the message body xml</returns>       public BusinessMessage Receive(int nTimeOut)       {             try             {                   string sQueuePath = MessageInfo.QueueName;                   if (!MessageQueue.Exists(sQueuePath))                   {                         // queue doesn't exist so throw exception                         throw new Exception("ReceiveError"                               + sQueuePath                               + " queue does not                               exist.");                   }                   // Init the queue                   MessageQueue oQueue = new                         MessageQueue(sQueuePath);                   ((XmlMessageFormatter)oQueue.Formatter)                         .TargetTypes =                         new Type[]{typeof(BusinessMessage)};                   // receive the message, timeout in only 5                   // seconds -- TODO: this should probably change                   System.Messaging.Message oRawMessage =                         oQueue.Receive(new TimeSpan(0, 0,                         nTimeOut));                   // extract the body and cast it to our                   // BusinessMessage type so we can return it                   BusinessMessage oMessageBody =                         (BusinessMessage)oRawMessage.Body;                   MessageInfo = oMessageBody;                   return oMessageBody;             }             catch (Exception e)             {                   throw new BaseException(this, 0, e.Message, e,                               false);             }       }    } 

Sending Traces via Sockets

After creating the Messenger class, RemoteTracerService.RemoteTrace first retrieves the MessageInfo property to populate the message contents. The message contents are then populated and sent to the message using Send. From this point, we could return control back to the trace originator . However, for demo purposes, I also send the trace to a socket server on the network. I do this by setting my host, ip, and port, and calling my utility method Utilities.SendSocketStream . This method creates a connection with the specified host and if successful, sends the trace message as a byte stream.

Listing 2.17 Sample Socket Routine for sending any message.
 public static string SendSocketStream(string sHost, int nPort, string sMessage) {    TcpClient oTcpClient = null;    string sAck = null;    int nBytesRead = 0;    NetworkStream oStream = null;    try    {          oTcpClient = new TcpClient();          Byte[] baRead = new Byte[100];          oTcpClient.Connect(sHost, nPort);          // Get the stream, convert to bytes          oStream = oTcpClient.GetStream();          // We could have optionally used a streamwriter and reader          //oStreamWriter = new StreamWriter(oStream);          //oStreamWriter.Write(sMessage);          //oStreamWriter.Flush();          // Get StreamReader to read strings instead of bytes          //oStreamReader = new StreamReader(oStream);          //sAck = oStreamReader.ReadToEnd();          // send and receive the raw bytes without a stream writer          // or reader          Byte[] baSend = Encoding.ASCII.GetBytes(sMessage);          // now send it          oStream.Write(baSend, 0,  baSend.Length);          // Read the stream and convert it to ASCII          nBytesRead = oStream.Read(baRead, 0, baRead.Length);          if (nBytesRead > 0)          {                sAck = Encoding.ASCII.GetString(baRead, 0, nBytesRead);          }    }    catch(Exception ex)    {          throw new BaseException(null, 0, ex.Message, ex, false);    }    finally    {          if (oStream != null)                oStream.Close();          if (oTcpClient != null)                oTcpClient.Close();    }    return sAck; } 

Do not be overwhelmed by the amount of code shown here. If you haven't worked with either message queuing or the .NET network libraries, you can select another implementation. These transports are not a requirement. You could have simply written your trace message (once received by the Web service) to a file somewhere. This just shows a few options for being a little more creative and creating what could become a rather robust feature of your application's health monitoring. Keep in mind that whatever transport you use to display or store your trace messages can and will throw exceptions. Typically, exceptions should not be thrown back to the trace originator because that would defeat the purpose of tracing. Remote trace errors should never halt a running application, and your code should take this into consideration .

Building a Remote Trace Viewer

Now that we have a custom trace listener (to send trace messages remotely) and a trace receiver Web service (to receive trace messages remotely), how do we view them? Again, this is completely up to you. In the following code, I show a rather slimmed-down version of the production TraceViewer that is implemented in the Product X application we will cover in Chapter 6. In the following code, I use three System.Windows.Forms.DataGrid controls to display streamed, queued, and status messages. The controls are each bound to a grid using a System.Data.DataSet that is dynamically created in Visual Studio .NET. The DataSet was created from a corresponding XML schema file we created (see the technology backgrounder in Chapter 5 for information on XML schemas and automated DataSet creation). Two System.Threading.Timer objects are used to provide a threaded means of receiving our trace messages, both from a message queue and from a socket client. For a full listing, please download the complete source for the RemoteTraceViewer.

Listing 2.18 Sample Remote Trace Listener viewer (GUI).
[View full width]
 public class frmSocketServer : System.Windows.Forms.Form {    . . .    private static TcpListener oListener = null;    private static Socket oSocket = null;    . . .    private System.Threading.Timer oQueuedTraceTimer = null;    private System.Threading.Timer oActiveTraceTimer = null;    . . .    private System.Windows.Forms.DataGrid ActiveTraceGrid;    private static TraceInfo dsActiveTraceData = null;    private static TraceInfo dsActiveTraceDataCopy = null;    private static TraceInfo dsQueuedTraceData = null;    private System.Windows.Forms.DataGrid QueuedTraceGrid;    private System.Windows.Forms.DataGrid StatusGrid;    private static TraceInfo dsQueuedTraceDataCopy = null;    public frmSocketServer()    {          //          // Required for Windows Form Designer support          //          InitializeComponent();          frmSocketServer.dsActiveTraceData = new TraceInfo();          frmSocketServer.dsActiveTraceDataCopy = new TraceInfo();          frmSocketServer.dsQueuedTraceData = new TraceInfo();          frmSocketServer.dsQueuedTraceDataCopy = new TraceInfo();    }    . . .    /// <summary>    /// The main entry point for the application.    /// </summary>    [STAThread]    static void Main()    {          Application.Run(new frmSocketServer());    }    private void cmdListen_Click(object sender, System.EventArgs e)    {          try          {                cmdListen.Enabled = false;                cmdStop.Enabled = true;                cmdRefresh.Enabled = true;                if (chkEnableQueued.Checked)                      oQueuedTraceTimer = new                            System.Threading.Timer(new                     TimerCallback(ProcessQueuedTrace), null, 0, 40000);                if (chkEnabledStreamed.Checked)                      oActiveTraceTimer = new                            System.Threading.Timer(new                     TimerCallback(ProcessActiveTrace),                     null, 0,                    System.Threading.Timeout.Infinite);                }                catch (Exception err)                {                      EventLog.WriteEntry("...", "Trace Error: " +                                  err.StackTrace);                }          }          private void cmdStop_Click(object sdr, System.EventArgs e)          {                StopListening();          }          /// <summary>          /// Delegated Event Method for Timer to process Queued          /// trace messages          /// </summary>          /// <param name="state"></param>          static void ProcessQueuedTrace(Object state)          {                EventLog oElog = new EventLog("Application",                      Dns.GetHostName(), "TraceViewMain");                Messenger oMessenger = new Messenger();                BusinessMessage oMessageIn = oMessenger.MessageInfo;                BusinessMessage oMessageOut;                try                {                      // must set the message type we are looking                      // for, this looks in the correct queue                      oMessageIn.MessageType = "trace";                      while (true)                      {                        // grab the message from the queue               WriteStatus(DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), "Listening for trace messages on the trace queue...");                      oMessageOut = oMessenger.Receive(oMessageIn, 10);                      string sSource = oMessageOut.UserId;                      string sDate =                      DateTime.Now.ToShortDateString();                      string sTime =                      DateTime.Now.ToShortTimeString();                      string sMessage = oMessageOut.MessageText;                            sMessage = sMessage.Replace('\n', '-');                      frmSocketServer.dsQueuedTraceData                                  .TraceMessage                                  .AddTraceMessageRow(sDate, sTime,                                        sSource, sMessage);                      frmSocketServer.dsQueuedTraceData                                  .TraceMessage                                  .AcceptChanges();                }          }          catch (Exception e)          {                // exception was probably thrown when no message                // could be found/timeout expired                if (e.Message.StartsWith("Timeout"))                {          WriteStatus(DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), "Timeout expired listening for messages on trace queue.");                }                else                {                      oElog.WriteEntry("SocketServer - Error Occurred                            During Message Receipt and Processing: "                            + e.ToString());                }          }    }    private void StopListening()    {          cmdListen.Enabled = true;          cmdStop.Enabled = false;          cmdRefresh.Enabled = false;          if (oSocket != null)          {          WriteStatus(DateTime.Now.ToShortDateString(),                      DateTime.Now.ToShortTimeString(),                            "Closing Socket ..." +                oSocket.LocalEndPoint.ToString());                oSocket.Close();                oSocket = null;          }          if (oListener != null)          {          WriteStatus(DateTime.Now.ToShortDateString(),          DateTime.Now.ToShortTimeString(),                            "Stopping Listener ..." +                oListener.LocalEndpoint.ToString());                oListener.Stop();                oListener = null;          }          if (oQueuedTraceTimer != null)                oQueuedTraceTimer.Dispose();          if (oActiveTraceTimer != null)                oActiveTraceTimer.Dispose();    }    /// <summary>    /// Delegated event method to process socket streamed trace    /// messages    /// </summary>    /// <param name="state"></param>    static void ProcessActiveTrace(Object state)    {          EventLog oElog = new EventLog("Application",                      Dns.GetHostName(), "TraceViewMain");          string sSource = null;          int nDelimPos = 0;          try          {                if (oListener == null)                {                      long lIP =                            Dns.GetHostByName(Dns.GetHostName()).AddressList[0] .Address;                      IPAddress ipAd = new IPAddress(lIP);                      oListener = new TcpListener(ipAd, 8001);                      oListener.Start();          WriteStatus(DateTime.Now.ToShortDateString(),                     DateTime.Now.ToShortTimeString(), "The server is running at port 8001. graphics/ccc.gif .."); WriteStatus(DateTime.Now.ToShortDateString(),                     DateTime.Now.ToShortTimeString(), "The local End                     point is  :" + oListener.LocalEndpoint);                      while (true)                      {  WriteStatus(DateTime.Now.ToShortDateString(),                      DateTime.Now.ToShortTimeString(),                      "Waiting for a connection on : "                                    + oListener.LocalEndpoint);                      oSocket = oListener.AcceptSocket();          WriteStatus(DateTime.Now.ToShortDateString(),                      DateTime.Now.ToShortTimeString(),                      "Connection accepted from " +                      oSocket.RemoteEndPoint);                      // prepare and receive byte array                      byte[] baBytes = new byte[1000];                      int k = oSocket.Receive(baBytes);                      WriteStatus(DateTime.Now.ToShortDateString(),                      DateTime.Now.ToShortTimeString(), "Received                      Message...");                     // let's do it the easy way                     string sReceivedBuffer =                                 Encoding.ASCII.GetString(baBytes, 0, baBytes.Length);                     WriteStatus(DateTime.Now.ToShortDateString(),                     DateTime.Now.ToShortTimeString(),                                 sReceivedBuffer);                     ASCIIEncoding asen = new ASCIIEncoding();                     oSocket.Send(asen.GetBytes("trace received"));                     nDelimPos = sReceivedBuffer.IndexOf(":");                     sSource = sReceivedBuffer.Substring(0,                        nDelimPos);                     string sDate =                           DateTime.Now.ToShortDateString();                     string sTime =                           DateTime.Now.ToShortTimeString();                     string sMessage =                           sReceivedBuffer.Substring(nDelimPos + 1, sReceivedBuffer.Length - (nDelimPos + 1));                     sMessage = sMessage.Replace('\n', '-');                     frmSocketServer.dsActiveTraceData                                    .TraceMessage                                   .AddTraceMessageRow(sDate, sTime,                                       sSource, sMessage);                     frmSocketServer.dsActiveTraceData                                    .TraceMessage                                    .AcceptChanges();                     }               }         }         catch (Exception e)         {               if (e.Message.StartsWith("A blocking operation"))               {          WriteStatus(DateTime.Now.ToShortDateString(),               DateTime.Now.ToShortTimeString(), "Socket listener was               canceled by the system.");               }               else               {                     System.Windows.Forms.MessageBox.Show("Error During Active Trace Listening: " +                           e.Message);                     oElog.WriteEntry("Error Occurred During Message Streaming"                           + e.ToString());               }         }         finally         {               if (oSocket != null)               {                     WriteStatus(...)                     oSocket.Close();                     oSocket = null;               }               if (oListener != null)               {                     WriteStatus(...)                     oListener.Stop();                     oListener = null;               }         }    }    private void cmdClear_Click(object sender, System.EventArgs e)    {         frmSocketServer.dsActiveTraceDataCopy.Clear();         frmSocketServer.dsQueuedTraceDataCopy.Clear();    }    /// <summary>    /// Adds a new message to the status tab    /// </summary>    /// <param name="sDate"></param>    /// <param name="sTime"></param>    /// <param name="sMessage"></param>    private static void WriteStatus(string sDate, string sTime,                                  string sMessage)    {         frmSocketServer.dsActiveTraceData                        .StatusMessage                        .AddStatusMessageRow(sDate, sTime, sMessage);         frmSocketServer.dsActiveTraceData                        .StatusMessage                        .AcceptChanges();    }    private void cmdRefresh_Click(object sender, System.EventArgs e)    {          // copy active (streamed) grid's data and bind to grid          ActiveTraceGrid.TableStyles.Clear();          frmSocketServer.dsActiveTraceDataCopy = (TraceInfo)              frmSocketServer.dsActiveTraceData.Copy();          ActiveTraceGrid.DataSource =                      frmSocketServer.dsActiveTraceDataCopy                               .Tables["TraceMessage"];          // copy queued (streamed) grid's data and bind to grid          QueuedTraceGrid.TableStyles.Clear();          frmSocketServer.dsQueuedTraceDataCopy = (TraceInfo)            frmSocketServer.dsQueuedTraceData.Copy();          QueuedTraceGrid.DataSource = frmSocketServer                      .dsQueuedTraceDataCopy                      .Tables["TraceMessage"];          // same for status . . .          // refresh all grids          ActiveTraceGrid.Refresh();          QueuedTraceGrid.Refresh();          StatusGrid.Refresh();          // this is absolutely required if you want to begin using          // the grid styles in code          // format the active trace grid          if (frmSocketServer.dsActiveTraceDataCopy.Tables.Count > 0)          {                if (ActiveTraceGrid.TableStyles.Count == 0)                {                      ActiveTraceGrid.TableStyles.Add(new                            DataGridTableStyle(true));                      ActiveTraceGrid.TableStyles[0]                                  .MappingName = "TraceMessage";                      FormatMessageGrid(ActiveTraceGrid, true);                }          }          // format the queued trace grid          if (frmSocketServer.dsQueuedTraceDataCopy.Tables.Count > 0)          {                if (QueuedTraceGrid.TableStyles.Count == 0)                {                      QueuedTraceGrid.TableStyles.Add(new                            DataGridTableStyle(true));                      QueuedTraceGrid.TableStyles[0]                                  .MappingName = "TraceMessage";                      FormatMessageGrid(QueuedTraceGrid, true);                }          }          // same for status    }    private void FormatMessageGrid(System.Windows.Forms.DataGrid oGrid,                      bool bIncludeSourceCol)    {          // if column styles haven't been set, create them..          if (oGrid.TableStyles[0].GridColumnStyles.Count == 0)          {               oGrid.TableStyles[0].GridColumnStyles.Add(new                     DataGridTextBoxColumn());               oGrid.TableStyles[0].GridColumnStyles.Add(new                     DataGridTextBoxColumn());               oGrid.TableStyles[0].GridColumnStyles.Add(new                     DataGridTextBoxColumn());               if (bIncludeSourceCol)          oGrid.TableStyles[0].GridColumnStyles.Add(new                     DataGridTextBoxColumn());          }          oGrid.TableStyles[0].GridColumnStyles[0].Width = 90;          // you must set each columnstyle's mappingname so that          // other properties can be set since this is bound          oGrid.TableStyles[0].GridColumnStyles[0]                      .MappingName = "Date";          oGrid.TableStyles[0].GridColumnStyles[0]                      .HeaderText = "Date";          oGrid.TableStyles[0].GridColumnStyles[1].Width = 90;          // you must set each columnstyle's mappingname so that          // other properties can be set since this is bound          oGrid.TableStyles[0].GridColumnStyles[1]                     .MappingName = "Time";          oGrid.TableStyles[0].GridColumnStyles[1]                     .HeaderText = "Time";          . . .          // format Source and Message columns styles ...    }    private void cmdTest_Click(object sender, System.EventArgs e)    {          try          {                throw new BaseException(this, 0,                            "This is a test 1,2,3,4,5",                            new Exception("this is the chained message",                                  null), true);          }          catch (Exception ex)          {                Console.Out.WriteLine(ex.Message);                //do nothing          }    } 

To run the RemoteTraceViewer, select Listen. This will start the timer threads , which in turn call ProcessActiveTrace and ProcessQueueTrace . Each will listen and receive messages, and will add each message to a DataSet. To test your remote tracing, select the Test button. This will throw a nested exception, which will call your remote trace Web service. Once received, both timer threads should pick up the message and display it on each grid accordingly . Several hundred pages could probably be devoted to explaining the building of a production-ready remote tracing utility but this example should get you started in right direction.

.NET Patterns. Architecture, Design, and Process
.NET Patterns: Architecture, Design, and Process
ISBN: 0321130022
EAN: 2147483647
Year: 2003
Pages: 70 © 2008-2017.
If you may any questions please contact us: