Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Programmatically install windows service failed.

$
0
0

 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.



Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>