none
Programmatically install windows service failed. RRS feed

  • Question

  •  I wish that it is a correct place. I want to install a windows service programmatically. It means that I type the command

    MyApplication.exe -install

    My code failed in this fashion but is oaky if I stepped into the code in debug mode in VS 2013. I followed the example at stackoverflow.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Configuration.Install;
    using System.Diagnostics;
    using System.Linq;
    using System.Reflection;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MessagingTestApplication
    {
        static class Program
        {
            public static string serviceName { get; set; }
    
            [MTAThread]
            static void Main(string[] args)
            {
                serviceName = "MyServiceName";
                var service = new TestService();
                if (args.Length == 0)
                { 
                    if(!Environment.UserInteractive)
                    {
                        var servicesToRun = new ServiceBase[] { service };
                        ServiceBase.Run(servicesToRun);
                    }
                    else
                    {
                        // local debug only
                        Console.WriteLine("Running as a Console Application");
                        MessagingTestApplication.TestApplication.Start();
                    }
                }
                else if(args.Length ==1)
                {
                    switch (args[0])
                    {
                        case "-install":
                            InstallService();
                            StartService();
                            break;
                        case "-uninstall":
                            StopService();
                            UninstallService();
                            break;
                        default:
                            throw new NotImplementedException();
                    }
                }
            }
    
            private static void UninstallService()
            {
                if (!IsInstalled()) return;
                try
                {
                    using (AssemblyInstaller installer = GetInstaller())
                    {
                        IDictionary state = new Hashtable();
                        try
                        {
                            installer.Uninstall(state);
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
    
            private static void InstallService()
            {
                if (IsInstalled()) return;
    
                try
                {
                    using (AssemblyInstaller installer = GetInstaller())
                    {
                        IDictionary state = new Hashtable();
                        try
                        {
                            installer.Install(state);
                            installer.Commit(state);
                        }
                        catch
                        {
                            try
                            {
                                installer.Rollback(state);
                            }
                            catch { }
                            throw;
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
    
            private static bool IsInstalled()
            {
                try
                {
                    var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);
                    if (serviceExists == false) return false;
                    return true;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return false;
                }
            }
    
            private static bool IsRunning()
            {
                using (ServiceController controller =
                    new ServiceController(serviceName))
                {
                    if (!IsInstalled()) return false;
                    return (controller.Status == ServiceControllerStatus.Running);
                }
            }
    
            private static AssemblyInstaller GetInstaller()
            {
                AssemblyInstaller installer = new AssemblyInstaller(
                    typeof(TestService).Assembly, null);
                installer.UseNewContext = true;
                return installer;
            }
    
            private static void StartService()
            {
                if (!IsInstalled()) return;
    
                using (ServiceController controller =
                    new ServiceController(serviceName))
                {
                    try
                    {
                        if (controller.Status != ServiceControllerStatus.Running)
                        {
                            controller.Start();
                            controller.WaitForStatus(ServiceControllerStatus.Running,
                                TimeSpan.FromSeconds(10));
                            Console.WriteLine("Service {0} started.",serviceName);
                        }
                    }
                    catch (InvalidOperationException ex)
                    {
                        Console.WriteLine("Service start error {0} ",ex.Message);
                    }
                }
            }
    
            private static void StopService()
            {
                // if (!IsInstalled()) return;
                using (ServiceController controller =
                    new ServiceController(serviceName))
                {
                    try
                    {
                        if (controller.Status != ServiceControllerStatus.Stopped)
                        {
                            controller.Stop();
                            controller.WaitForStatus(ServiceControllerStatus.Stopped,
                                 TimeSpan.FromSeconds(10));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Service stop error {0} ", ex.Message);
                    }
                }
            }
        }
    }
    In another word, I set the argument "-install" in the project property, everything is fine. But it is unluck in command line. Thanks for help.


    • Edited by ardmore Thursday, February 20, 2014 10:22 PM
    Thursday, February 20, 2014 10:20 PM

Answers

  • Hello,

    If we use the InstallUtil.exe to install a service, then the service must be use the windows service template.

    Have a try to create your service by the windows service project and add reference in your console application. Run the CMD as administrator. With the link, I make a demo:

    using System;
    
    using System.Collections;
    
    using System.Collections.Generic;
    
    using System.Configuration.Install;
    
    using System.Linq;
    
    using System.ServiceProcess;
    
    using System.Text;
    
    using System.Threading.Tasks;
    
    using TestService;
    
    
    namespace IntsallServiceProgrammatically
    
    {
    
        class Program
    
        {
    
            public static string serviceName { get; set; }
    
    
            [MTAThread]
    
            static void Main(string[] args)
    
            {
    
                if (args.Length == 0)
    
                {
    
                    //Run your service normally.
    
                    //ServiceBase[] ServicesToRun = new ServiceBase[] { new ServiceExample() };
    
                    //ServiceBase.Run(ServicesToRun);
    
                }
    
                else if (args.Length == 1)
    
                {
    
                    switch (args[0])
    
                    {
    
                        case "-install":
    
                            InstallService();
    
                            StartService();
    
                            break;
    
                        case "-uninstall":
    
                            StopService();
    
                            UninstallService();
    
                            break;
    
                        default:
    
                            throw new NotImplementedException();
    
                    }
    
                }
    
            }
    
    
            private static bool IsInstalled()
    
            {
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        ServiceControllerStatus status = controller.Status;
    
                    }
    
                    catch
    
                    {
    
                        return false;
    
                    }
    
                    return true;
    
                }
    
            }
    
    
            private static bool IsRunning()
    
            {
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    if (!IsInstalled()) return false;
    
                    return (controller.Status == ServiceControllerStatus.Running);
    
                }
    
            }
    
    
            private static AssemblyInstaller GetInstaller()
    
            {
    
                AssemblyInstaller installer = new AssemblyInstaller(
    
                    typeof(ServiceExample).Assembly, null);
    
                installer.UseNewContext = true;
    
                return installer;
    
            }
    
    
            private static void InstallService()
    
            {
    
                if (IsInstalled()) return;
    
    
                try
    
                {
    
                    using (AssemblyInstaller installer = GetInstaller())
    
                    {
    
                        IDictionary state = new Hashtable();
    
                        try
    
                        {
    
                            installer.Install(state);
    
                            installer.Commit(state);
    
                        }
    
                        catch
    
                        {
    
                            try
    
                            {
    
                                installer.Rollback(state);
    
                            }
    
                            catch { }
    
                            throw;
    
                        }
    
                    }
    
                }
    
                catch
    
                {
    
                    throw;
    
                }
    
            }
    
    
            private static void UninstallService()
    
            {
    
                if (!IsInstalled()) return;
    
                try
    
                {
    
                    using (AssemblyInstaller installer = GetInstaller())
    
                    {
    
                        IDictionary state = new Hashtable();
    
                        try
    
                        {
    
                            installer.Uninstall(state);
    
                        }
    
                        catch
    
                        {
    
                            throw;
    
                        }
    
                    }
    
                }
    
                catch
    
                {
    
                    throw;
    
                }
    
            }
    
    
            private static void StartService()
    
            {
    
                if (!IsInstalled()) return;
    
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        if (controller.Status != ServiceControllerStatus.Running)
    
                        {
    
                            controller.Start();
    
                            controller.WaitForStatus(ServiceControllerStatus.Running,
    
                                TimeSpan.FromSeconds(10));
    
                        }
    
                    }
    
                    catch
    
                    {
    
                        throw;
    
                    }
    
                }
    
            }
    
    
            private static void StopService()
    
            {
    
                if (!IsInstalled()) return;
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        if (controller.Status != ServiceControllerStatus.Stopped)
    
                        {
    
                            controller.Stop();
    
                            controller.WaitForStatus(ServiceControllerStatus.Stopped,
    
                                 TimeSpan.FromSeconds(10));
    
                        }
    
                    }
    
                    catch
    
                    {
    
                        throw;
    
                    }
    
                }
    
            }
    
        }
    
    }
    

    The result:

    Install:

    Uninstall:

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by ardmore Tuesday, February 25, 2014 1:42 AM
    Monday, February 24, 2014 9:37 AM
    Moderator

All replies

  • Hello,

    >>My code failed in this fashion but is oaky if I stepped into the code in debug mode in VS 2013.

    When you use command, does it throw any error message? And could you please share how you define the TestService class so that we can make an exact test with it?

    And have a try to run the cmd as administrator account to check whether it will success.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, February 21, 2014 9:00 AM
    Moderator
  • I am the administrator. There was no error. I also tried InstallUtil.exe but failed.

    The service file code:

     partial class TestService : ServiceBase
        {
            public TestService()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
                System.Timers.Timer aTimer = new System.Timers.Timer(500); //500 MilliSeconds
                // Hook up the Elapsed event for the timer.
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                // Set the Interval to 2 seconds (2000 milliseconds).
                //aTimer.Interval = 600000;  //10 minutes //2000; //2 seconds (2000 mili seconds)
                aTimer.AutoReset = false;
                aTimer.Enabled = true;
                // Keep the timer alive until the end of Main.  This allows OnStart to close in a timely fashion.
                GC.KeepAlive(aTimer);
            }
    
            private void OnTimedEvent(object sender, ElapsedEventArgs e)
            {
                TestApplication.Start();
            }
    
            protected override void OnStop()
            {
                TestApplication.StopImmediate();
            }

     UPDATE:

    One thing I want to mention is the project type is console application rather than windows service but it contains a windows service class. My purpose is to convert console application to windows service and also keep the nature of console type thus I can debug it easily and install it programmatically. Is it a problem?


    • Edited by ardmore Saturday, February 22, 2014 2:34 PM add more explantation
    Friday, February 21, 2014 10:00 PM
  • Hello,

    If we use the InstallUtil.exe to install a service, then the service must be use the windows service template.

    Have a try to create your service by the windows service project and add reference in your console application. Run the CMD as administrator. With the link, I make a demo:

    using System;
    
    using System.Collections;
    
    using System.Collections.Generic;
    
    using System.Configuration.Install;
    
    using System.Linq;
    
    using System.ServiceProcess;
    
    using System.Text;
    
    using System.Threading.Tasks;
    
    using TestService;
    
    
    namespace IntsallServiceProgrammatically
    
    {
    
        class Program
    
        {
    
            public static string serviceName { get; set; }
    
    
            [MTAThread]
    
            static void Main(string[] args)
    
            {
    
                if (args.Length == 0)
    
                {
    
                    //Run your service normally.
    
                    //ServiceBase[] ServicesToRun = new ServiceBase[] { new ServiceExample() };
    
                    //ServiceBase.Run(ServicesToRun);
    
                }
    
                else if (args.Length == 1)
    
                {
    
                    switch (args[0])
    
                    {
    
                        case "-install":
    
                            InstallService();
    
                            StartService();
    
                            break;
    
                        case "-uninstall":
    
                            StopService();
    
                            UninstallService();
    
                            break;
    
                        default:
    
                            throw new NotImplementedException();
    
                    }
    
                }
    
            }
    
    
            private static bool IsInstalled()
    
            {
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        ServiceControllerStatus status = controller.Status;
    
                    }
    
                    catch
    
                    {
    
                        return false;
    
                    }
    
                    return true;
    
                }
    
            }
    
    
            private static bool IsRunning()
    
            {
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    if (!IsInstalled()) return false;
    
                    return (controller.Status == ServiceControllerStatus.Running);
    
                }
    
            }
    
    
            private static AssemblyInstaller GetInstaller()
    
            {
    
                AssemblyInstaller installer = new AssemblyInstaller(
    
                    typeof(ServiceExample).Assembly, null);
    
                installer.UseNewContext = true;
    
                return installer;
    
            }
    
    
            private static void InstallService()
    
            {
    
                if (IsInstalled()) return;
    
    
                try
    
                {
    
                    using (AssemblyInstaller installer = GetInstaller())
    
                    {
    
                        IDictionary state = new Hashtable();
    
                        try
    
                        {
    
                            installer.Install(state);
    
                            installer.Commit(state);
    
                        }
    
                        catch
    
                        {
    
                            try
    
                            {
    
                                installer.Rollback(state);
    
                            }
    
                            catch { }
    
                            throw;
    
                        }
    
                    }
    
                }
    
                catch
    
                {
    
                    throw;
    
                }
    
            }
    
    
            private static void UninstallService()
    
            {
    
                if (!IsInstalled()) return;
    
                try
    
                {
    
                    using (AssemblyInstaller installer = GetInstaller())
    
                    {
    
                        IDictionary state = new Hashtable();
    
                        try
    
                        {
    
                            installer.Uninstall(state);
    
                        }
    
                        catch
    
                        {
    
                            throw;
    
                        }
    
                    }
    
                }
    
                catch
    
                {
    
                    throw;
    
                }
    
            }
    
    
            private static void StartService()
    
            {
    
                if (!IsInstalled()) return;
    
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        if (controller.Status != ServiceControllerStatus.Running)
    
                        {
    
                            controller.Start();
    
                            controller.WaitForStatus(ServiceControllerStatus.Running,
    
                                TimeSpan.FromSeconds(10));
    
                        }
    
                    }
    
                    catch
    
                    {
    
                        throw;
    
                    }
    
                }
    
            }
    
    
            private static void StopService()
    
            {
    
                if (!IsInstalled()) return;
    
                using (ServiceController controller =
    
                    new ServiceController("ServiceExample"))
    
                {
    
                    try
    
                    {
    
                        if (controller.Status != ServiceControllerStatus.Stopped)
    
                        {
    
                            controller.Stop();
    
                            controller.WaitForStatus(ServiceControllerStatus.Stopped,
    
                                 TimeSpan.FromSeconds(10));
    
                        }
    
                    }
    
                    catch
    
                    {
    
                        throw;
    
                    }
    
                }
    
            }
    
        }
    
    }
    

    The result:

    Install:

    Uninstall:

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by ardmore Tuesday, February 25, 2014 1:42 AM
    Monday, February 24, 2014 9:37 AM
    Moderator
  • Very cool! I will try it in my machine. By the way, how did you make the demo? Witch software did you use?
    Monday, February 24, 2014 1:35 PM
  • Hello,

    It is LICEcap.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, February 25, 2014 1:23 AM
    Moderator