views:

224

answers:

1

Hello.

I have two Windows services written in C#. One service is "Console Application" and second one is "Windows Application" (can't change it). Both service applications can be executed in few modes (depending on command line arguments and Environment.UserInteractive flag):

  • when (Environment.UserInteractive == false) and...
    • when no cmd-line parameter is provided - standard out-generated code (required for SCM) is executed - ServiceBase.Run(ServicesToRun)
  • when (Environment.UserInteractive == true) and...
    • when "-i" cmd-line parameter is provided - service application installs itself (something like installutil -i [scv_app])
    • when "-u" cmd-line parameter is provided - service application uninstalls itself (something like installutil -u [scv_app])
    • when "-c" cmd-line parameter is provided - service is executed in "console" mode (for debug purposes)

Both services use static method from class library to choose and process described execution path. However, I have one problem in this class library - when application has type "Windows Application", then Console.WriteLine() has no visible effect. In that case I could use Win32 AttachConsole() or something like that, but I prefer to show summarized messages via MessageBox.Show(). Thus, I think that in class library I need to know whether application is "Console Application" or "Windows Application"... Do you have any idea how to do it?

At the beginning, instead of trying to detect app type I have tried to write something like that:

if (string.IsNullOrEmpty(Console.Title) == false) Console.WriteLine(msg); 

It works in Win7 but it does not work under Win2k3. So maybe there is a better way to detect if Console.WriteLine(msg) / Console.ReadLine works as expected? I’ve seen some other suggestions (sublinked here), but none of them looks good to me. I am looking for "nice" solution (!= p/invoke; != accessing any Console object property (e.g. Title) inside a try/catch block).

A: 
  1. Windows services are not supposed to have ui. This includes consoles and messageboxes.

With that out of the way...

Have you considered hooking up an appropriate trace listener to System.Diagnostics.Trace.TraceListeners? Based on your command line you could add a MessageBox tracelistener or a tracelistener that dumps trace messages to a console? You'll be leveraging built-in debugging mechanisms that have been extensively tested and are, in their own way, extremely extensible as well. You'll also implicitly get to distinguish between messages that are displayed in release mode vs. messages displayed in debug mode (via System.Diagnostics.Trace.Write() or System.Diagnostics.Debug.Write()).

Greg D