Changing a Command Line Application to a Windows Service, and confusion about static methods

  • Thread starter Thread starter PaulCutcliffe
  • Start date Start date
P

PaulCutcliffe

Guest
I've been working on a command line .Net application, and I decided it would work better as a Windows Service.

So I firstly followed this article and made a simple Windows Service with an EventLog and a Timer: docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

Then I added a project to my solution using the .Net Windows Service template, and I set it up with an EventLog and a Timer, just like in the simple example in the article. Then I copied most of the code from the original application's main() function into the service's OnTimer() method, along with all the additional methods that were called from that code, and I was pleasantly surprised at how few problems I encountered.

I do have one outstanding problem, however. My OnTimer() method starts with this line:

eventLogMyService.WriteEntry("MyService running hourly checks...", EventLogEntryType.Information, eventId++);

This code runs happily, but I have a method that logs any output to the console and also to a log file that is sent by FTP and emailed on completion of the program, and I would like to add some code to this method so this output can also be written to the eventLog as well. The method looks like this:

static void LogResult(string strResult)
{
eventLogMyService.WriteEntry(strResult, EventLogEntryType.Information, eventId++); // <= CS0120 Error on this line
Console.WriteLine(strResult);
sbResults.AppendLine(strResult);
}

But this code won't compile, and raises the following error:

CS0120 C# An object reference is required for the non-static field, method, or property

It's complaining about both eventLogMyService and the eventId.

If I remove static from the method, then those error disappear but I get a whole bunch of other errors. This leads me to realise that while I understand in theory what the word static means (i.e. that something that is static works on the class rather than an instantiated object of that class), I don't really understand how that relates to what I'm doing here.

Can anyone point me in the right direction?

Thanks. :-)

Continue reading...
 
Back
Top