C#(VS2008)服务编写-安装和部署

1.创建一个空白解决方案。

2.在解决方案下面添加两个Windows服务:WXSmsGuardNew(保护服务),WXSmsMainNew(主服务).

3.第一个服务作为保护服务,服务上添加两个控件:System.Timers.Timer和System.ServiceProcess.ServiceController

由于System.Timers.Timer不会显示在工具栏中无法直接拖到服务中,故而我们找到服务设计器页面WXSmsGuardNew.Designer.cs,将手动构造System.Timers.Timer控件

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.timer1 = new System.Timers.Timer();
            this.sc = new System.ServiceProcess.ServiceController();
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
            // 
            // timer1
            // 
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            // 
            // sc
            // 
            this.sc.ServiceName = "WXSmsGuardNew";
            // 
            // WXSmsGuardNew
            // 
            this.ServiceName = "WXSmsGuardNew";
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();

        }

        #endregion

        private System.Timers.Timer timer1;
        private System.ServiceProcess.ServiceController sc;

将 ServiceController控件的属性Name改为"sc",ServiceName改为"WXSmsMainNew",因为着这个控件是跟踪主服务用的所以设置为主服务的服务名

保护服务中,Timer监控主服务运行状态

        public WXSmsGuardNew()
        {
            //验证服务器证书回调自动验证
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidate);
            InitializeComponent();
        }
        public bool RemoteCertificateValidate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
        protected override void OnStart(string[] args)
        {
            WriteLog("保护服务已开启");
        }

        protected override void OnStop()
        {
            WriteLog("保护服务已关闭");
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer1.Enabled = false;
            sc.Refresh();
            if (sc.Status != ServiceControllerStatus.Running)
            {
                sc.Start();
                WriteLog("发现发送已关闭,已经开启");
            }
            timer1.Enabled = true;
        }

主服务则负责专门做需要做的事情,如实时发送短信,或者其他逻辑

public WXSmsMainNew()
        {
            //验证服务器证书回调自动验证
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidate);
            InitializeComponent();
        }
        public bool RemoteCertificateValidate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
        protected override void OnStart(string[] args)
        {
            WriteLog("发送服务已开启");
        }

        protected override void OnStop()
        {
            WriteLog("发送服务已关闭");
        }

        #region 获取参数
        public string GetConfig(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public string GetConfig(int index)
        {
            return ConfigurationManager.ConnectionStrings[index].ConnectionString;
        }

        public int GetConfigCont()
        {
            return ConfigurationManager.ConnectionStrings.Count;
        }
        #endregion

        #region timer 事件
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer1.Enabled = false;

            int num = GetConfigCont();
            for (int i = 1; i < num; i++)
            {
                SendSms ssms = new SendSms();
                bool b = ssms.SendWX(GetConfig(i));
                if (!b)
                {
                    this.Stop();
                }
            }

            timer1.Enabled = true;
        }
        #endregion

辅助方法,记录日志

        #region 写日志
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        public void WriteLog(string msg)
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\log\";
            Directory.CreateDirectory(path);
            for (int i = 1; ; i++)
            {
                string fileName = string.Format("{0}WXSendServer{1}-{2}.txt", path, DateTime.Now.ToString("yyyyMMdd"), i);
                if (File.Exists(fileName))
                {
                    FileInfo fileInfo = new FileInfo(fileName);
                    if (fileInfo.Length >= 2048 * 1024)//>=2M
                    {
                        continue;
                    }
                }
                string msgInfo = string.Format("{0} {1}
", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg);
                File.AppendAllText(fileName, msgInfo);
                break;
            }
        }
        #endregion

以上完成了代码编写。

4.然后配置安装及服务信息

在两个服务的设计界面点鼠标右键有个"添加安装程序",点击之后会生成ProjectInstaller.cs文件,将此文件自动生成的控件于服务相对应

5.安装和部署

解决方案添加安装项目

在安装项目上右键--视图--文件系统中,右键--添加--项目输出,将两个服务均作为主输出添加进去

然后在安装项目上右键--视图--自定义操作,将两个主输出均添加到对应的步骤下.

最后,生成安装项目,会在安装项目的目录下生成两个文件,安装其中任何一个均可

原文地址:https://www.cnblogs.com/sky-gfan/p/5218007.html