創建自動發郵件的服務
一.創建服務
1.在VS中,菜單欄上,選擇文件->新建->項目,選擇“Windows 服務”,對項目重命名
2.在編輯菜單上,選擇“查找和替換”將Service1改成ServiceEmail;
3.在Service1.cs[Design]中,將SeriviceNamede 名稱屬性設置爲ServiceEmail;
4.將解決方案管理器中,將Service1.cs重命名爲ServiceEmail.cs
二.向服務添加功能,將自定義事件日誌功能添加到服務中
1.雙擊打開ServiceEmail.cs,從工具箱的組件將EventLog組件拖動到設計器中,查看代碼
2.在ServiceEmail類中添加“事件日誌”對象的聲明,並添加或編輯構造函數定義自定義事件日誌
public ServiceEmail()
{
InitializeComponent();
this.AutoLog = false;
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
//不存在就創建新的
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailSourceLog");
}
eventLog1.Source = "EmailSource";
eventLog1.Log = "EmailSourceLog";
}
3.定義服務啓動時停止時發生的情況,找到創建項目時自動改寫的OnStart方法與OnStop方法
4.修改其中的代碼,添加定時和發送郵件的代碼,具體如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;
namespace ServiceEmail
{
public partial class ServiceEmail : ServiceBase
{
public ServiceEmail()
{
InitializeComponent();
this.AutoLog = false;
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
//不存在就創建新的
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailSourceLog");
}
eventLog1.Source = "EmailSource";
eventLog1.Log = "EmailSourceLog";
}
System.Timers.Timer timer;//計時器
private static readonly string CurrentPath=AppDomain.CurrentDomain.BaseDirectory;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Interval = 3000;//設置計時器事件間隔執行時間
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
eventLog1.WriteEntry("In OnStart");
//保存日誌文件
string path = CurrentPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
FileStream filestream = new FileStream(path,FileMode.Append,FileAccess.Write);
StreamWriter sw = new StreamWriter(filestream);
sw.WriteLine("Start :"+DateTime.Now.ToShortDateString());
sw.Flush();
sw.Close();
filestream.Close();
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop");
}
public void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (e.SignalTime.Hour == 16)
{
SendText();
}
//if (e.SignalTime.Hour == 0 && e.SignalTime.Minute == 0 && e.SignalTime.Second == 0)
//{
// SendText();
//}
}
public void SendText()
{
try
{
SmtpClient MailClient = new SmtpClient("smtp-mail.outlook.com");
MailClient.EnableSsl = true;
//發送郵件的郵箱與密碼
MailClient.Credentials = new System.Net.NetworkCredential("***@outlook.com", "***");
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("***@outlook.com");
Msg.To.Add(new MailAddress("***@outlook.com"));
Msg.Subject = "testSub";
Msg.Body = "testBody";
string userState = "test message1";
MailClient.SendAsync(Msg, userState);
}
catch (SmtpException ex)
{
string _err = ex.Message;
}
}
}
}
三.向服務添加安裝程序
1.在解決方案資源管理器中,打開ServiceEmail.cs,選擇查看設計器,選擇添加安裝程序,命名該組件爲ProjectInstaller
2.在ProjectInstaller的設計界面中,選擇serviceInstaller1的屬性窗口,將ServiceName設置爲ServiceEmail,在名稱中將DisplayName設置爲ServiceEmail
3.將StartType設置爲AutoMatic
4.在設計器中,選擇serviceProcessInstaller1,將Account屬性設置爲LocalSystem,這將使得本地服務賬戶上安裝運行該服務
四.在解決方案資源管理器中,點擊生成項目
五.安裝服務
1. 在 Windows 7 和 Windows Server 中,打開“開始”菜單中“Visual Studio 工具”下的“開發人員命令提示”。 在 Windows 8 或 Windows 8.1 中,選擇“開始”屏幕上的“Visual Studio 工具”圖塊,然後使用管理憑據運行開發人員命令提示。 (如果使用鼠標,右鍵單擊“開發人員命令提示”,然後選擇“以管理員身份運行”。)
2. 在命令提示窗口中,導航到包含項目輸出的文件夾。 例如,在“我的文檔”文件夾下,導航到 Visual Studio 2013\Projects\MyNewService\bin\Debug。
3. 輸入以下命令:
installutil.exe ServiceEmail.exe
4.如果遇到錯誤'installutil.exe' is not recognized as an internal or external command,
operable program or batch file. 修改命令爲“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe ServiceEmail.exe”即可,其中“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\”是對應於你電腦中installutil.exe的路徑位置。
5.如果遇到錯誤“An exception occurred during the Install phase.
System.Security.SecurityException: The source was not found, but some or all eve
nt logs could not be searched. Inaccessible logs: Security.”是因爲沒有以管理員身份運行開發人員命令提示,需要右鍵單擊“開發人員命令提示”,然後選擇“以管理員身份運行”
六.啓動與運行服務
1. 在 Windows 中,打開“開始”屏幕或“開始”菜單,然後輸入 services.msc。
你應該會看見ServiceEmail列於“服務”窗口中。 服務窗口中的ServiceEmail
2. 在“服務”窗口中,打開你的服務的快捷菜,然後選擇“啓動”。
3. 打開該服務的快捷菜單,然後選擇“停止”。
4. (可選)你可以在命令行中使用 net startServiceName 和 net stopServiceName 命令來啓動和停止你的服務。
七.驗證服務的事件日誌輸出
1. 在 Visual Studio 中,打開“服務器資源管理器”(鍵盤:Ctrl+Alt+S),然後訪問本地計算機的“事件日誌”節點。
2. 找到EmailSourceLog列表並將它展開。 你會看到你的服務執行的兩個操作(啓動和停止)的條目。
使用事件查看器查看事件日誌條目。
有關服務的調試,可以去參閱下面的網址
http://msdn.microsoft.com/zh-cn/library/cktt23yw.aspx
http://msdn.microsoft.com/zh-cn/library/7a50syb3(v=vs.110).aspx