views:

104

answers:

4

Hello, How do I make my Windows Service to work in the following way...

1.) Automatically start after it installs

2.) Automatically start even if we simply double click on the executable

In other words,I dont want to use the "NET START","SC" commands and dont want to start it through the services console. I just want my Service to auto-install and auto start itself...plus start itself automatically when the executable is double clicked.

Thanks.

+3  A: 

Have a look at ServiceController class.

You can use it in commited event like this :

[RunInstaller(true)]
public class ServiceInstaller : Installer
{
    string serviceName = "MyServiceName";

    public ServiceInstaller()
    {
        var processInstaller = new ServiceProcessInstaller();
        var serviceInstaller = new ServiceInstaller();

        processInstaller.Account = ...;
        processInstaller.Username = ...;
        processInstaller.Password = ...;

        serviceInstaller.DisplayName = serviceName;
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = serviceName;

        this.Installers.Add(processInstaller);
        this.Installers.Add(serviceInstaller);

        this.Committed += new InstallEventHandler(ServiceInstaller_Committed);
    }

    void ServiceInstaller_Committed(object sender, InstallEventArgs e)
    {
        // Auto Start the Service Once Installation is Finished.
        var controller = new ServiceController(serviceName);
        controller.Start();
    }
}
Incognito
I still have to use the "NET START" or "SC"....How do I start the service by double clicking on it?
Josh
@Josh You can just double clock on executable file and run the service.What you can do is just to make another executable which will use ServiceController to start your services which is not started. You can check how MS SQL Server is doing that. There is separate program which stops and starts the service if you won't want to use MMC.
Incognito
A: 

My post here shows how to have your Windows service install itself from the command line using a -install option. You could extend this logic to have a -start option and then create a shortcut on the desktop that includes that option.

Matt Davis
-start option is what I actually need.
Josh
+1  A: 

You can add command line arguments that call the installer ( use ManagedInstallerClass.InstallHelper()), and code to start the service...

 public class DataImportService : ServiceBase
 {
     // ----------- Other code -----------

     static void Main(string[] args)
     {
       if (args.Length == 0) 
       {
            InstallService(false, argValue); break;
            StartService();
       }
       else
       {
            string arg0 = args[0],
            switchVal = arg0.ToUpper(),
            argValue = arg0.Contains(":") ?
            arg0.Substring(arg0.IndexOf(":")) : null;

            switch (switchVal.Substring(0, 1))
            {
                //Install Service and run
                case ("I"): case ("-I"): case ("/I"):
                    InstallService(true, argValue); break;

                 // Start Service
                case ("S"): case ("-S"): case ("/S"):
                    StartService();
                default: break;

                 // Install & Start Service
                case ("IS"): case ("-IS"): case ("/IS"):
                    InstallService(false, argValue); break;
                    StartService();

                // Uninstall Service
                case ("U"): case ("-U"): case ("/U"):
                    InstallService(false, argValue); break;

                default: break;                   
            }
        }

     private static void InstallService(bool install,  string argFileSpec)
     {
        string fileSpec = Assembly.GetExecutingAssembly().Location;
        if (!String.IsNullOrEmpty(argFileSpec)) fileSpec = argFileSpec;
        // ------------------------------------------------------------
        string[] installerParams =
            install? new string[] { fileSpec } :
                     new string[] { "/u", fileSpec };
        ManagedInstallerClass.InstallHelper(installerParams);
     }

     private void StartService()
     {
        var ctlr  = new ServiceController();
        ctlr.ServiceName = "MyService";    // hard code the service name
        // Start the service
        ctlr.Start();           
     }
}
Charles Bretana
What about starting the service? I need to start the service by just double clicking on it...
Josh
@Josh, Use the `ServiceController()` class to start and stop services. You will need to decide how to code this Main routine to do it... That's up to you...
Charles Bretana
+2  A: 

Take a look at the Topshelf project (http://topshelf-project.com) and eliminate all the complexity of writing Windows services in .NET. It handles all the self-registration and eliminates all the dependencies on service code from your application.

It's also open-source and hosted on GitHub, making it easy to adapt to any application.

(full disclosure, I am one of the authors on the project)

Chris Patterson
Tried your project...but the SERVICE argument doesn't work.It's like a normal windows service.it says "---------------------------Windows Service Start Failure---------------------------Cannot start service from the command line or a debugger. A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.---------------------------OK ---------------------------".
Josh
You need to create your own EXE, you can follow the play-by-play here: http://topshelf-project.com/documentation/getting-started/
Chris Patterson
Thanks...And the download links aren't working on your website..
Josh
Please see my question here....http://stackoverflow.com/questions/3256535/topshelf-difference-between-configureserviceinisolation-and-configureservice
Josh