• C#下的Windows服务通用壳程序(三)


    壳程序组成:

    (1)入口程序类:

    View Code
    //================================================================================
    //  FileName: Program.cs
    //  Desc: Windows服务壳程序入口类。
    //
    //  Called by
    //
    //  Auth:杨勇(jeason1914@gmail.com)
    //  Date: 2010-1-19
    //================================================================================
    //  Change History
    //================================================================================
    //  Date  Author  Description
    //  ----    ------  -----------------
    //
    //================================================================================
    //  Copyright (C) 2004-2009 Jeason Young Corporation
    //================================================================================
    using System;
    using System.Collections.Generic;
    using System.ServiceProcess;
    using System.Configuration.Install;
    using System.Text;
    using System.Reflection;
    
    using iPower.WinService.Config;
    using iPower.WinService.Logs;
    namespace iPower.WinService.Shell
    {
        /// <summary>
        /// Windows服务壳程序入口类。
        /// </summary>
        static class Program
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            /// <param name="args">命令行参数。</param>
            public static void Main(string[] args)
            {
                using (WinServiceLog servLog = new WinServiceLog(ServiceConfig.ModuleConfig))
                {
                    string svcName = ServiceConfig.ModuleConfig.ServiceName;
                    try
                    {
                        bool flag = true;
                        if (args != null && args.Length > 0)
                        {
                            string assemblyName = Assembly.GetExecutingAssembly().ManifestModule.Name;
                            switch (args[0].ToLower())
                            {
                                case "-i":
                                case "-install":
                                    {
                                        servLog.ContentLog(string.Format("开始安装[{0}]服务...", svcName));
                                        if (!ServiceIsExisted(svcName))
                                        {
                                            ManagedInstallerClass.InstallHelper(new string[] { assemblyName });
                                            ServiceController c = new ServiceController(svcName);
                                            c.Start();
                                            servLog.ContentLog(string.Format("安装服务[{0}]成功。", svcName));
                                        }
                                        else
                                        {
                                            servLog.ContentLog(string.Format("服务[{0}]已经存在,无需重复安装。", svcName));
                                        }
                                    }
                                    break;
                                case "-u":
                                case "-uninstall":
                                    {
                                        if (ServiceIsExisted(svcName))
                                        {
                                            servLog.ContentLog(string.Format("开始卸载{0}服务...", svcName));
                                            ManagedInstallerClass.InstallHelper(new string[] { "/u", assemblyName });
                                            servLog.ContentLog(string.Format("卸载[{0}]服务成功。", svcName));
                                        }
                                        else
                                        {
                                            servLog.ContentLog(string.Format("服务{0}已经卸载。", svcName));
                                        }
                                        flag = false;
                                    }
                                    break;
                                default:
                                    {
                                        servLog.ContentLog(string.Format("命令 {0} 不存在。", args));
                                        flag = false;
                                    }
                                    break;
                            }
                        }
    
                        if (flag)
                        {
                            servLog.ContentLog(string.Format("开始启动[{0}]服务...", svcName));
                            ServiceBase.Run(new ServiceBase[] { new ServiceMain() });
                            servLog.ContentLog(string.Format("[{0}]服务启动成功。", svcName));
                        }
                    }
                    catch (Exception e)
                    {
                        servLog.ContentLog(string.Format("安装[{0}]服务失败。", svcName));
                        servLog.ErrorLog(e);
                    }
                }
    
            }
            /// <summary>
            /// 检查指定的服务是否存在。
            /// </summary>
            /// <param name="svcName">要查找的服务名字。</param>
            /// <returns></returns>
            static bool ServiceIsExisted(string svcName)
            {
                ServiceController[] services = ServiceController.GetServices();
                if (services != null && services.Length > 0)
                {
                    for (int i = 0; i < services.Length; i++)
                    {
                        if ((services[i] != null) && (services[i].ServiceName == svcName))
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
    }

    (2)Windows服务主类(windows服务的核心)。

    View Code
    //================================================================================
    //  FileName: ServiceMain.cs
    //  Desc:Window服务主类。
    //
    //  Called by
    //
    //  Auth:杨勇(jeason1914@gmail.com)
    //  Date: 2010/1/17
    //================================================================================
    //  Change History
    //================================================================================
    //  Date  Author  Description
    //  ----    ------  -----------------
    //
    //================================================================================
    //  Copyright (C) 2004-2009 Jeason Young Corporation
    //================================================================================
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Text;
    using System.Timers;
    using System.Reflection;
    using System.Threading;
    using System.ComponentModel;
    using System.ServiceProcess;
    
    using iPower.WinService;
    using iPower.WinService.Config;
    using iPower.WinService.Jobs;
    using iPower.WinService.Logs;
    namespace iPower.WinService.Shell
    {
        /// <summary>
        /// Window服务主类。
        /// </summary>
        public sealed class ServiceMain : ServiceBase
        {
            #region 成员变量,构造函数,析购函数
            Container components = null;
            Dictionary<string, IJob> allJobs;
            WinServiceLog servlog = null;
            System.Timers.Timer mTimer;
            string[] args = null;
            /// <summary>
            /// 构造函数。
            /// </summary>
            public ServiceMain()
            {
                try
                {
                    //初始化组件对象。
                    this.components = new Container();
                    //初始化服务任务集合。
                    this.allJobs = new Dictionary<string, IJob>();
                    //服务名称。
                    this.ServiceName = ServiceConfig.ModuleConfig.ServiceName;
                    //服务日志初始化。
                    this.servlog = new WinServiceLog(ServiceConfig.ModuleConfig);
                }
                catch (Exception ex)
                {
                    //错误日志记录。
                    this.servlog.ErrorLog(ex);
                }
                finally
                {
                    //定时器初始化。
                    this.mTimer = new System.Timers.Timer();
                    this.mTimer.AutoReset = true;
                    this.mTimer.Enabled = false;
                    this.mTimer.Interval = ModuleConst.CONST_DOU_TIMEINTERVAL;
                    this.mTimer.Elapsed += this.OnTimerElapsed;
                }
            }
            #endregion
    
            #region 重载服务。
            /// <summary>
            /// 启动服务。
            /// </summary>
            /// <param name="args"></param>
            protected override void OnStart(string[] args)
            {
                lock (this)
                {
                    this.args = args;
                    //加载任务配置。
                    this.LoadJobs();
                    //启动服务。
                    base.OnStart(this.args);
                    //启动任务。
                    this.startJobs(this.args);
                }
            }
            /// <summary>
            /// 停止服务。
            /// </summary>
            protected override void OnStop()
            {
                lock (this)
                {
                    //停止定时器。
                    this.mTimer.Stop();
                    #region 服务停止。
                    if (this.allJobs != null && this.allJobs.Count > 0)
                    {
                        foreach (KeyValuePair<string, IJob> kvp in this.allJobs)
                        {
                            if (kvp.Value != null)
                            {
                                try
                                {
                                    ((IJob)kvp.Value).Stop();
                                }
                                catch (Exception x)
                                {
                                    this.servlog.ErrorLog(x);
                                }
                            }
                        }
                    }
                    #endregion
                    base.OnStop();
                }
            }
            /// <summary>
            /// 暂停。
            /// </summary>
            protected override void OnPause()
            {
                lock (this)
                {
                    //停止定时器。
                    this.mTimer.Stop();
                    #region 服务暂停。
                    if (this.allJobs != null && this.allJobs.Count > 0)
                    {
                        foreach (KeyValuePair<string, IJob> kvp in this.allJobs)
                        {
                            if (kvp.Value != null)
                            {
                                try
                                {
                                    ((IJob)kvp.Value).Pause();
                                }
                                catch (Exception x)
                                {
                                    this.servlog.ErrorLog(x);
                                }
                            }
                        }
                    }
                    #endregion
                    base.OnPause();
                }
            }
            /// <summary>
            /// 继续。
            /// </summary>
            protected override void OnContinue()
            {
                this.startJobs(this.args);
                base.OnContinue();
            }
            #endregion
    
            #region 辅助函数。
            /// <summary>
            /// 加载WinServiceJob。
            /// </summary>
            private void LoadJobs()
            {
                lock (this)
                {
                    Dictionary<string, bool> configJobs = ServiceJobsConfig.ModuleConfig.AllJobs;
                    if (configJobs != null && configJobs.Count > 0)
                    {
                        foreach (KeyValuePair<string, bool> job in configJobs)
                        {
                            try
                            {
                                if (job.Value && !string.IsNullOrEmpty(job.Key) && !this.allJobs.ContainsKey(job.Key))
                                {
                                    //获取配置。
                                    JobConfiguration configuration = new JobConfiguration(job.Key);
                                    if (configuration != null && !string.IsNullOrEmpty(configuration.ModuleAssembly) && !string.IsNullOrEmpty(configuration.ModuleClassName))
                                    {
                                        string moduleAssembly = configuration.ModuleAssembly;
                                        Assembly executingAssembly = null;
                                        if (Assembly.GetExecutingAssembly().FullName.StartsWith(moduleAssembly))
                                        {
                                            executingAssembly = Assembly.GetExecutingAssembly();
                                        }
                                        else
                                        {
                                            executingAssembly = Assembly.Load(moduleAssembly);
                                        }
                                        //加载程序集。
                                        if (executingAssembly != null)
                                        {
                                            IJob wjob = executingAssembly.CreateInstance(configuration.ModuleClassName) as IJob;
                                            if (wjob != null)
                                            {
                                                this.allJobs.Add(job.Key, wjob);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception x)
                            {
                                this.servlog.ErrorLog(x);
                            }
                        }
                    }
                }
            }
            /// <summary>
            /// 启动任务。
            /// </summary>
            /// <param name="args"></param>
            private void startJobs(string[] args)
            {
                if (this.allJobs != null && this.allJobs.Count > 0)
                {
                    foreach (KeyValuePair<string, IJob> kvp in this.allJobs)
                    {
                        if (!string.IsNullOrEmpty(kvp.Key) && (kvp.Value != null))
                        {
                            try
                            {
                                ((IJob)kvp.Value).Start(args);
                            }
                            catch (Exception e)
                            {
                                this.servlog.ErrorLog(e);
                            }
                        }
                    }
                    //启动定时器。
                    this.mTimer.Start();
                }
            }
            /// <summary>
            /// 定时函数。
            /// </summary>
            /// <param name="s"></param>
            /// <param name="e"></param>
            private void OnTimerElapsed(object s, ElapsedEventArgs e)
            {
                lock (this)
                {
                    try
                    {
                        //停止定时器。
                        this.mTimer.Stop();
                        if (this.allJobs != null && this.allJobs.Count > 0)
                        {
                            foreach (KeyValuePair<string, IJob> kvp in this.allJobs)
                            {
                                try
                                {
                                    IJob job = kvp.Value;
                                    if (job != null && job.CanRun())
                                    {
                                        new Thread(new ThreadStart(delegate()
                                        {
                                            job.Run();
                                        })).Start();
                                    }
                                }
                                catch (Exception x)
                                {
                                    this.servlog.ErrorLog(x);
                                }
    
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.servlog.ErrorLog(ex);
                    }
                    finally
                    {
                        //启动定时器。
                        this.mTimer.Start();
                    }
                }
            }
            #endregion
    
            #region 重载。
            /// <summary>
            /// 
            /// </summary>
            /// <param name="disposing"></param>
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (this.mTimer != null)
                    {
                        this.mTimer.Stop();
                        this.mTimer.Elapsed -= this.OnTimerElapsed;
                        this.mTimer.Dispose();
                        this.mTimer = null;
                    }
                    this.components.Dispose();
                }
                base.Dispose(disposing);
            }
            #endregion
        }
    }

    (3)windows服务的安装类(windows服务安装方法)。

    View Code
    //================================================================================
    //  FileName: WinServiceInstaller.cs
    //  Desc:Widows服务安装配置类。
    //
    //  Called by
    //
    //  Auth:杨勇(jeason1914@gmail.com)
    //  Date: 2010-1-19
    //================================================================================
    //  Change History
    //================================================================================
    //  Date  Author  Description
    //  ----    ------  -----------------
    //
    //================================================================================
    //  Copyright (C) 2004-2009 Jeason Young Corporation
    //================================================================================
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.ServiceProcess;
    using System.Configuration.Install;
    using iPower.WinService.Config;
    namespace iPower.WinService.Shell
    {
        /// <summary>
        /// Widows服务安装配置类。
        /// </summary>
        [RunInstaller(true)]
        public class WinServiceInstaller :Installer
        {
            #region 构造函数,析购函数
            IContainer components = null;
            ServiceProcessInstaller serviceProcessInstaller = null;
            ServiceInstaller serviceInstaller = null;
            /// <summary>
            /// 构造函数。
            /// </summary>
            public WinServiceInstaller()
            {
                this.InitializeComponent();
            }
            /// <summary>
            /// 析构函数。
            /// </summary>
            ~WinServiceInstaller()
            {
            }
            #endregion
    
            #region 重载
            /// <summary>
            /// 
            /// </summary>
            /// <param name="disposing"></param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (this.components != null))
                    this.components.Dispose();
                base.Dispose(disposing);
            }
            #endregion
    
            void InitializeComponent()
            {
                this.serviceProcessInstaller = new ServiceProcessInstaller();
                this.serviceInstaller = new ServiceInstaller();
    
                string userName = ServiceConfig.ModuleConfig.Username;
                this.serviceProcessInstaller.Account = string.IsNullOrEmpty(userName) ? ServiceAccount.LocalSystem : ServiceAccount.User;
                if (!string.IsNullOrEmpty(userName))
                {
                    this.serviceProcessInstaller.Username = userName;
                    this.serviceProcessInstaller.Password = ServiceConfig.ModuleConfig.Password;
                }
    
                this.serviceInstaller.Description = ServiceConfig.ModuleConfig.Description;
                this.serviceInstaller.DisplayName = ServiceConfig.ModuleConfig.DisplayName;
                this.serviceInstaller.ServiceName = ServiceConfig.ModuleConfig.ServiceName;
                this.serviceInstaller.StartType = ServiceStartMode.Automatic;
    
                this.Installers.AddRange(new Installer[] { this.serviceProcessInstaller,
                                                           this.serviceInstaller});
            }
        }
    }

    (4)安装服务命令(可以用记事本写在bat文件中,注意bat文件的编码格式必须是ANSI,否则无法执行)

    iPower.WinService.Shell.exe -i

    (5)卸载服务命令

    iPower.WinService.Shell.exe -u

    己所不欲,勿施于人。

  • 相关阅读:
    07 监控100台服务器磁盘利用率
    算法提高 阮小二买彩票
    算法提高 日期计算
    算法提高 身份证号码升级
    算法提高 统计单词数
    算法提高 3000米排名预测
    算法提高 最长字符序列
    算法提高 种树
    算法训练 装箱问题
    算法训练 瓷砖铺放
  • 原文地址:https://www.cnblogs.com/jeason1914/p/3035624.html
Copyright © 2020-2023  润新知