Is running as Windows service or command-line?

  • Thread starter Thread starter Peter Rilling
  • Start date Start date
P

Peter Rilling

I have an EXE that I would like to be able to run from either the
command-line or as a windows service.

Is there a way that I can tell which context the program is running in?
Basically, if it runs as a service, I would want it to call ServiceBase.Run
(which will then call the execution logic). If it is run at the
command-line, I simply want it to run as a normal application.
 
Peter,

The answer is YES !!! (*WOOHOO*). In short - you can acheive what you are
trying to do by passing a commandline parameter to your exe (DebugMode in my
case below).

The design pattern is slightly different between 2.0 and 1.1 though.

Let me describe the 2.0 pattern first.

You'd have a Service1.cs and a Program.cs right? The following code goes
into Program.cs -----

static void Main(string[] args)
{
ServiceBase[] ServicesToRun;

if (args.Length > 0)
{
if (args[0].ToString() == "DebugMode")
{
Service1 svc = new Service1();
svc.EntryPoint(null) ;
System.Windows.Forms.Application.Run();
svc.ExitPoint();
}
else
{
ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
}
}

The trick is to add a reference to System.Windows.Forms .. and use the
Application.Run so that it starts the message loop on it.


Okay so the above being fairly simple here is the 1.1 pattern -----------

The 1.1 pattern involves adding something like ---

<MTAThread()> _
Shared Sub Main()
Dim MyService As New Service

If String.Compare(Microsoft.VisualBasic.Command(), "DebugMode",
True).Equals(0) Then
DebugModeMode = True
End If
If Not Environment.OSVersion.Platform.Equals(PlatformID.Win32NT)
Then
DebugModeMode = True
End If
......
and then
If DebugModeMode Then
MyService.OnStart(Nothing)

Application.Run()

MyService.OnStop()
Else

// Run like a service ... autogenerated code comes here

End If

Sorry one of the above is in C# and the other is in VB.NET :) I didn't know
which one you'd prefer so I mixed n matched :)

One last thing - in Visual Studio - on the project settings - change Debug
Command Line Parameters to "DebugMode" this will allow you to develop a
windows service with the same ease as it lets you do a windows application.

- Sahil Malik
http://dotnetjunkies.com/weblog/sahilmalik
http://blogs.apress.com/authors.php?author=Sahil Malik
 
Back
Top