Home > Articles > Programming > Windows Programming

This chapter is from the book

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).

    02fig08.jpgFigure 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 XXXlistener 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.

/// <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("Receive–Error"
                              + 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).

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020