Giter Club home page Giter Club logo

kc.installservice's Introduction

InstallService

This library contains code for installing a .NET service in an automated fashion. It is only for use with .NET Framework.

Installing

  • .Net Framework: Install-Package KC.InstallService

Getting Started

using System;
using System.Linq;
using System.ServiceProcess;
using KC.InstallServiceNS;
using System.Configuration.Install;
using System.Threading;
using System.IO;
using System.ComponentModel;

namespace Example.InstallServiceNS {

    public class Service : ServiceBase {
        public static string Name = "Example.InstallService";

        //To try this out, you should change the debug arguments to match one of the arguments below.
        //This can be done in Visual Studio from ProjectProperties.Debug.CommandLineArguments
        //NOTE: You'll need to run Visual Studio as an admin for this to work.
        static void Main(string[] args) {
            try {
                if (args != null && args.Any(x => x == "/i")) {
                    InstallService.Install(Name);
                    return;
                }
                if (args != null && args.Any(x => x == "/stop")) {
                    InstallService.TryStopService(Name);
                    return;
                }
                if (args != null && args.Any(x => x == "/start")) {
                    InstallService.TryStopService(Name);
                    return;
                }
                if (args != null && args.Any(x => x == "/u")) {
                    InstallService.Uninstall(Name);
                    return;
                }

                if (Environment.UserInteractive) {
                    DoSomething();
                }
                else {
                    ServiceBase.Run(new Service());
                }
            }
            catch (Exception ex) {
                File.AppendAllText(Path.Combine("C:\\", "failedToStart.txt"), ex.ToString());
            }
            finally {
                if (Environment.UserInteractive) {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            }
        }

        public Service() {
            this.CanStop = true;
            this.ServiceName = Name;
        }

        private static bool m_Running;
        private static object lockRunning = new object();
        public static bool Running {
            get {
                lock (lockRunning)
                    return m_Running;
            }
            set {
                lock (lockRunning)
                    m_Running = value;
            }
        }

        protected override void OnStart(string[] args) {
            base.OnStart(args);

            if (Running) {
                return;
            }
            var t = new Thread(() => {
                DoSomething();
            });
            t.Name = Name;
            t.Start();
        }

        protected override void OnStop() {
            base.OnStop();
            Running = false;
            //Give the app up to 5 seconds to shut down.
            //This is coincidentally the default amount of time windows gives us
            //when the PC is rebooting, so this shouldn't go any higher.
            System.Threading.Thread.Sleep(5000);
        }

        private static void DoSomething() {
            Running = true;
            while (Running) {
                try {
                    File.AppendAllText(@"C:\InstallService.txt", $"{Environment.NewLine}{new Random().Next()}");
                }
                catch {
                    //This isn't real, so we don't need logging. We can also ignore the Thread.Sleep mechanism below for the same reason.
                }
                Thread.Sleep(3000);
            }
        }

    }

    [RunInstaller(true)]
    public class TheServiceInstaller : Installer {
        public TheServiceInstaller() {
            var serviceProcessInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.DisplayName = Service.Name;
            serviceInstaller.Description = Service.Name;
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.DelayedAutoStart = true;
            serviceInstaller.ServiceName = Service.Name;
            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}

kc.installservice's People

Contributors

caseymarquis avatar

Stargazers

 avatar

Watchers

 avatar

kc.installservice's Issues

Installation fails if the path to the assembly has spaces

If the path to the assembly has spaces a service installation will fail.

Changing line 39 of InstallService.cs to:
if (!RunCmdProcess.RunProcess(bestInstallUtil.FullName, $"\"{execFilePath}\"", Path.GetFullPath(".\\"))) {

Resolves the issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.