views:

15

answers:

1

Suppose an executable named ConsoleOrService.exe is written in C#. It currently is a hybrid. I can just start it on the command line, or I can install it using the .Net's installutil ConsoleOrService.exe and then start the service. I would like a third option: running it on the command line like so: ConsoleOrService.exe --install and have it do all of the work.

  1. Is this possible?
  2. Is this hard?
  3. How can I get started?

Thank you, and let me know if there are questions please.

+1  A: 

It's actually quite simple. I've used it in many of my own services (in fact, ALL of my services are capable of doing their own install/uninstall. I control it with a command-line switch, such as /install or /uninstall.

The installation is performed like this:

private static void InstallService()
{
 var ti  = new System.Configuration.Install.TransactedInstaller();
 var si  = new MyServiceInstaller();
 var cl  = new string[] { string.Format(CultureInfo.InvariantCulture, "/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location) };
 var ctx = new System.Configuration.Install.InstallContext(null, cl);

 ti.Installers.Add(si);
 ti.Context = ctx;
 ti.Install(new Hashtable());
}

The uninstallation is the same, except that you call ti.Uninstall(null); instead of ti.Install(...);.

My MyServiceInstaller is a class that inherits from the System.Configuration.Install.Installer class (as you would normally have in a service).

Mark
Nice, could you show us more details, for exemple how you handle the command line in program ?
Pierre 303
I assume this is part of it, I am sure that all sorts of nasty exceptions come up. To echo Pierre, if you do not mind sharing some more code, that would be very welcomed.
Hamish Grubijan
My command line handling is nothing more complex than an `if( args.Length > 0 ) { ... }` and a `switch( args[0] ) { ... }` in this particular project. I don't handle any exceptions specially, because there is a global handler for `AppDomain.CurrentDomain.UnhandledException` that does logging for me.
Mark