Creating a Windows Service with C#, concluded - Logging events
(Page 2 of 4 )
With the helper methods in place, actually logging events is a matter of calling Log(message). Typically you would put messages in OnStart() and OnStop() indicating service start and stop, and in this case you may want to log every time someone connects to the server. Add this line to OnStart():
this.Log(this.ServiceName + " Started");
And add this line to OnStop():
this.Log(this.ServiceName + " Stopped");
In the Start() method, inside the control loop, we need to check the number of bytes read to see if a request has been received and, if one has, to make a note of it. Add this line to the Start() method after the line reading “s.Send(time);”:
this.Log("Received request: " + bytesRead.ToString());
You have probably noticed that there are no try/catch blocks in this service. It would probably be wise to add one in our control loop! Wrap everything inside the while loop in a try statement, then in the catch, write to the event log, like this:
while (!this.isStopped)
{
try
{
s = this.listener.AcceptSocket();
incomingBuffer = new Byte[100];
bytesRead = s.Receive(incomingBuffer);
time = Encoding.ASCII.GetBytes(
System.DateTime.Now.ToString().ToCharArray());
s.Send(time);
this.Log("Received request: " + bytesRead.ToString
());
}
catch (Exception ex)
{
this.Log(ex);
}
}
Now that logging is complete, let’s move on to creating our controller application. Be sure you reinstall the service first to activate the changes we have made.
Next: Creating the Controller >>
More C# Articles
More By David Fells