VS2019 create Windows service

Posted by dominod on Tue, 04 Jan 2022 02:11:18 +0100

To write a daily report on the enterprise wechat every day, a robot is added to remind you to write a daily report regularly, so a local service is made.

1, Create enterprise wechat robot

Click on the top right of the group to add a robot

 

The Webhook address above will be used in the next three steps

2, Create project

1.VS create a new project Windows service

 2. Right click on the Service1 [design] interface to add the installer

The control as shown in the figure below appears

Click serviceInstaller1 to set the startup mode of the service and the service name displayed in the service list on the property panel

Click serviceProcessInstaller1 and set the service type to local mode in the property panel

 

OK, the creation of the project is completed, and the rest is to move the bricks

III. coding

1. Program. The Main method in CS is the starting point of the whole program, and can call multiple service programs. It is free to play here. The program we are currently writing will not be extended

 2. Daily report service. In the service code, OnStart and OnStop are executed only once, at the start and stop time respectively. In addition, there are OnContinue, OnPause, etc. for details, press F12 at ServiceBase to retrieve metadata.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                WriteLog("Service startup");
                ToDoSomeThings();

            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
                ServiceController serviceController = new ServiceController();
                if (serviceController.CanStop)
                {
                    serviceController.Stop();
                }
            }
        }

        protected override void OnStop()
        {
            try
            {
                this.WriteLog("End of service");
            }
            catch (Exception ex)
            {
                this.WriteLog(ex.Message);
                ServiceController serviceController = new ServiceController();
                if (serviceController.CanStop)
                {
                    serviceController.Stop();
                }
            }

        }

        /// <summary>
        ///Log
        /// </summary>
        /// <param name="LogContent"></param>
        private void WriteLog(string LogContent)
        {
            string FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Log.txt";
            FileStream fileStream = null;
            if (File.Exists(FilePath))
            {
                fileStream = new FileStream(FilePath, FileMode.Append);
            }
            else
            {
                fileStream = new FileStream(FilePath, FileMode.OpenOrCreate);
            }
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.WriteLine(DateTime.Now + System.Environment.NewLine + LogContent);

            streamWriter.Close();
            fileStream.Close();
            GC.Collect();
        }

        private void ToDoSomeThings()
        {
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
            // Set the time interval of the trigger time, which is set to 1 second here
            aTimer.Interval = 1000;
            aTimer.Enabled = true;

        }

        private void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // Get hour minute second. If it is equal to a certain value, start execution
            int intHour = e.SignalTime.Hour;
            int intMinute = e.SignalTime.Minute;
            int intSecond = e.SignalTime.Second;
            // The customized time is executed at 00:00:00
            int iHour = 18;
            int iMinute = 50;
            int iSecond = 00;
            // Set 00:00:00 every day to start executing the program
            if (intHour == iHour && intMinute == iMinute && intSecond == iSecond)
            {
                //Call the method you want to update
                WriteLog("Execute daily report function");
                Send();
            }
        }

        private void Send()
        {
            //The requested Webhook address of the enterprise wechat robot
            string url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxxx";
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            Encoding encoding = Encoding.UTF8;
            string param = "{ \"msgtype\": \"text\", \"text\": { \"content\": \"Write daily!!!!\" } }";
            byte[] bs = Encoding.UTF8.GetBytes(param);
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/json";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                Console.WriteLine(responseData);
            }
        }
    }
}

3. After the project is generated, the server can be deployed

4, Deploy local services

1. Find the generated project folder

2. Copy an installutil Exe to folder

 

3. Create a new notepad in the folder and edit it

cd /d "%~dp0"
InstallUtil.exe WindowsService1.exe
net start ReportService
cmd

 ​​​​​​​

 

 

4. Rename the new Notepad to install Bat for installing services

5. Create a new notepad and rename it uninstall Bat to uninstall the service

cd /d "%~dp0"
InstallUtil.exe /u WindowsService1.exe
cmd

 6. Run install. As an administrator Bat, the service will be installed, which can be found in the service list. The service name is the service name ReportService named in step 2 just now

 

V VS debugging

Debugging additional processes in VS

 

Additional adjustable

6, After development and commissioning

1. Execute uninstall as an administrator Bat uninstalls the debugging service

2. You can copy the generated project folder to the place you want to put it, and then execute install as an administrator Bat can be used

 

 

Topics: C# Front-end Windows IDE