jueves, 14 de mayo de 2020

Installing your own Windows Service



PROGRAM.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;  //ADD THIS PACKAGE

namespace MyService
{
    class Program
    {
        static void Main(string[] args)
        {
            var host = HostFactory.Run(front =>
            {
                front.RunAsLocalSystem();
                front.SetServiceName("FileUpload");
                front.SetDisplayName("File Update Service");
                front.SetDescription("Servicio local de File Update Service");

                front.Service<FileUpdate>(back => 
                {
                    back.ConstructUsing(service => new FileUpdate());
                    back.WhenStarted(service => service.Start());
                    back.WhenStopped(service => service.Stop());
                });
            });

            int outvalue = (int)Convert.ChangeType(host, host.GetTypeCode());

            Environment.ExitCode = outvalue;
        }
    }
}

/*INSTALL SERVICE
*
*   COPY CODE TO SOME FOLDER. EXAMPLE: C:\TMP\CODE\
*   RUN WINDOWS SHELL CONSOLE AS ADMINISTRATOR
*   C:> CD C:\TMP\CODE\
*   C:\TMP\CODE\> MYSERVICE.EXE INSTALL START
* UNINSTALL SERVICE
*   RUN WINDOWS SHELL CONSOLE AS ADMINISTRATOR
*   C:> CD C:\TMP\CODE\
*   C:\TMP\CODE\> MYSERVICE.EXE UNINSTALL 
*  
*/

====================================================
CLASS FILEUPLOAD

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace MyService
{
    class FileUpdate
    {
        private readonly Timer time;

        public FileUpdate()
        {
            time = new Timer(1000)
            {
                AutoReset = true
            };
            time.Elapsed += Time_Elapsed;
        }

        private void Time_Elapsed(object sender, ElapsedEventArgs e)
        {
            string line = string.Format("{0}\n", DateTime.Now.ToString());
            File.AppendAllText(@"C:\tmp\timer.log", line);
        }

        public void Start()
        {
            time.Start();
        }

        public void Stop()
        {
            time.Stop();
        }
    }
}