C#(VS2008)服務編寫-安裝和部署

來源:互聯網
上載者:User

標籤:

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}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg);                File.AppendAllText(fileName, msgInfo);                break;            }        }        #endregion

以上完成了代碼編寫。

4.然後配置安裝及服務資訊

在兩個服務的設計介面點滑鼠右鍵有個"添加安裝程式",點擊之後會產生ProjectInstaller.cs檔案,將此檔案自動產生的控制項於服務相對應

5.安裝和部署

解決方案添加安裝項目

在安裝項目上右鍵--視圖--檔案系統中,右鍵--添加--項目輸出,將兩個服務均作為主輸出添加進去

然後在安裝項目上右鍵--視圖--自訂動作,將兩個主輸出均添加到對應的步驟下.

最後,產生安裝項目,會在安裝項目的目錄下產生兩個檔案,安裝其中任何一個均可

 

C#(VS2008)服務編寫-安裝和部署

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.