簡單訊息通知

簡單訊息通知

參考了下列資料

如何在ASP.NET中下載檔案

結合之前寫的smtp發信及列舉

寫一下方便以後使用

目前提供四種訊息傳遞或記錄的方法。

1. 將訊息輸出成文字檔在客戶端下載。

2. 將訊息在存在主機端Log檔。

3. 將訊息在用電子郵件寄出。

4. 將訊息寫入資料庫,表格名稱為系統名+Log

參數定義如下:

LogFileName 存在主機端的log檔案名稱,包含完整路徑。
ErrorMessage 訊息內容。
ErrorType 訊息型態。
DealerEMail 訊息收件者的電子郵件。
SenderMail 發送者名稱,預設為TestServer@server.tw,不可回信。

函數列表:

/// 將訊息在客戶端下載.

public static void AlertMessageToClientFile(System.Web.UI.Page WebForm, string FileNameWhenUserDownload)

此函式有Response.End(),請置於程式碼最後一行以免資料無法回傳或指令無法執行。


public static void AlertMessageToClientFile(System.Web.UI.Page WebForm, string FileNameWhenUserDownload)
此函式有Response.End(),請置於程式碼最後一行以免資料無法回傳或指令無法執行。
函式說明:
/// 設定log檔路徑
public static void SetLogFilePath(string LogFName)
/// 設定收件人信箱.
public static void SetRecieveMailBox(string[] Email)
/// 設定寄件人信箱.
public static void SetSendMailBox(string Email)
/// 設定錯誤訊息.
public static void SetErrorMessage(string ClassName, string FuncName, Exception e)
/// 設定錯誤訊息.
public static void SetErrorMessage(Exception e)
/// 取得錯誤訊息.
public static string GetErrorMessage()
/// 設定訊息型態及內容.
public static void SetErrorMessage(string EMessage, MessageType MType)
/// 設定訊息內容.
public static void SetErrorMessage(string EMessage)
/// 最終輸出的訊息內容.
public static string GetResultSendMessage()
/// 將訊息在客戶端下載.
public static void AlertMessageToClientFile(System.Web.UI.Page WebForm, string FileNameWhenUserDownload)
/// 將訊息在存在指定主機端Log檔.
public static void AlertMessageToLogFile(string FileName)
/// 將訊息在存在預設主機端Log檔.
public static void AlertMessageToLogFile(System.Web.UI.Page WebForm)
/// 將訊息寄出到預設電子郵件.
public static void AlertMessageToEmail()
/// 將訊息寄出到指定電子郵件.
public static void AlertMessageToEmail(string[] RecieverEMail)
/// 將訊息寫入DB,表格名稱為系統名+Log.
public static void AlertMessageToDB(string ConnectString ,string SystemName,MessageType MType, string Message)

用法:


    {
        try
        {
            int[] result = new int[3];
            for (int i = 0; i < 10; i++)
                result[i] = i;
        }
        catch (Exception k)
        {
            string connectstring = ConfigurationManager.ConnectionStrings["TestConn"].ToString();
            //設定錯誤訊息內容及型態
            ErrorHandlingUtility.SetErrorMessage("測試錯誤", ErrorHandlingUtility.MessageType.錯誤);
            //將訊息寄出到指定電子郵件 aaa@bbb.com.tw
            ErrorHandlingUtility.AlertMessageToEmail(new string[] { "aaa@bbb.com.tw" });
            //將訊息在存在預設主機端Log檔,檔名為yyyyMMdd.txt.
            ErrorHandlingUtility.AlertMessageToLogFile(this);
            //將訊息在存在指定主機端Log檔,檔名為testlog.txt.
            ErrorHandlingUtility.AlertMessageToLogFile(Server.MapPath("./") + "testlog.txt");
            //ErrorHandlingUtility.CreateMessageTable(connectstring, "TestSystem");//建立log table
            //將指定訊息寫入DB,表格名稱為系統名+Log.
            ErrorHandlingUtility.AlertMessageToDB(connectstring, "TestSystem", ErrorHandlingUtility.MessageType.警告, "警告訊息");
            //將預設訊息寫入DB,表格名稱為系統名+Log.
            ErrorHandlingUtility.AlertMessageToDB(connectstring, "TestSystem");
            //將訊息在客戶端下載,檔名為ClientLog.txt.
            ErrorHandlingUtility.AlertMessageToClientFile(this, "ClientLog.txt");
            
        }
        

    }

以下為程式碼


using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Data.SqlClient;

/// <summary>
/// ErrorHandlingUtility 的摘要描述
/// </summary>
public static class ErrorHandlingUtility
{
    public static string LogFileName = string.Empty;
    public static string ErrorMessage = string.Empty;
    public static MessageType ErrorType = MessageType.無;
    public static List<string> DealerEMail = new List<string>();
    public static string LogFileNameByDate = DateTime.Now.ToString("yyyyMMdd") + ".txt";
    public static string SenderMail = "TestServer@server.tw";
    [Flags]
    public enum MessageType
    {
        無,
        訊息,
        警告,
        錯誤
    };
    #region 訊息設定
    /// <summary>
    /// 設定log檔路徑.
    /// </summary>
    /// <param name="LogFName">Name of the log F.</param>
    /// <param name="EMessage">The E message.</param>
    /// <param name="MType">Type of the M.</param>
    public static void SetLogFilePath(string LogFName)
    {
        LogFileName = (LogFName == string.Empty) ? string.Empty : LogFName;        
    }
    /// <summary>
    /// 設定收件人信箱.
    /// </summary>
    /// <param name="Email">The email.</param>
    public static void SetRecieveMailBox(string[] Email)
    {
        DealerEMail.AddRange(Email);
    }
    /// <summary>
    /// 設定寄件人信箱.
    /// </summary>
    /// <param name="Email">The email.</param>
    public static void SetSendMailBox(string Email)
    {
        SenderMail = Email;
    }
    /// <summary>
    /// 設定訊息型態及內容.
    /// </summary>
    /// <param name="EMessage">The E message.</param>
    /// <param name="MType">Type of the M.</param>
    public static void SetErrorMessage(string EMessage, MessageType MType)
    {
        ErrorMessage = (EMessage == string.Empty) ? string.Empty : EMessage;
        ErrorType = MType;
    }
    /// <summary>
    /// 設定訊息內容.
    /// </summary>
    /// <param name="EMessage">The E message.</param>
    public static void SetErrorMessage(string EMessage)
    {
        ErrorMessage = (EMessage == string.Empty) ? string.Empty : EMessage;
    }
    /// <summary>
    /// 設定錯誤訊息.
    /// </summary>
    /// <param name="ClassName">Name of the class.</param>
    /// <param name="FuncName">Name of the func.</param>
    /// <param name="e">The e.</param>
    public static void SetErrorMessage(string ClassName, string FuncName, Exception e)
    {
        string[] sep = new string[] { ":", "。" };
        string[] ErrorPool = e.ToString().Split(sep, StringSplitOptions.RemoveEmptyEntries);
        string Message = ErrorPool[0] + "(" + ErrorPool[1] + ")";
        //StartKiller(3);
        StringBuilder sb = new StringBuilder();
        ErrorType = MessageType.錯誤;
        sb.AppendLine("錯誤物件:" + ClassName.ToString());
        sb.AppendLine("程式函數:" + FuncName.ToString());
        sb.AppendLine("例外處理類型:" + e.GetType().ToString());
        sb.AppendLine("錯誤訊息:" + e.Message);
        sb.AppendLine("程式或物件名稱:" + e.Source);
        sb.AppendLine("產生錯誤程序:" + e.TargetSite.Name);
        sb.AppendLine("錯誤處:" + e.StackTrace);
        ErrorMessage = sb.ToString();
    }
   
    /// <summary>
    /// 設定錯誤訊息.
    /// </summary>
    /// <param name="e">The e.</param>
    public static void SetErrorMessage(Exception e)
    {
        string[] sep = new string[] { ":", "。" };
        string[] ErrorPool = e.ToString().Split(sep, StringSplitOptions.RemoveEmptyEntries);
        string Message = ErrorPool[0] + "(" + ErrorPool[1] + ")";
        //StartKiller(3);
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("例外處理類型:" + e.GetType().ToString());
        sb.AppendLine("錯誤訊息:" + e.Message);
        sb.AppendLine("程式或物件名稱:" + e.Source);
        //sb.AppendLine("產生錯誤程序:" + e.TargetSite.Name);
        sb.AppendLine("錯誤處:" + e.StackTrace);
        ErrorMessage = sb.ToString();
        ErrorType = MessageType.錯誤;
    }
    /// <summary>
    /// 取得錯誤訊息.
    /// </summary>
    /// <returns></returns>
    public static string GetErrorMessage()
    {
        return ErrorMessage;
    }
   
    #endregion
    #region 訊息發送
    /// <summary>
    /// 最終輸出的訊息內容.
    /// </summary>
    /// <returns></returns>
    public static string GetResultSendMessage()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("發送訊息日期:" + DateTime.Now.ToString("yyyyMMdd"));
        sb.AppendLine("訊息類型:" + ErrorType.ToString());
        sb.AppendLine("以下為訊息內容:");
        sb.AppendLine(ErrorMessage.ToString());
        return sb.ToString();
    }
    /// <summary>
    /// 將訊息在客戶端下載.
    /// </summary>
    /// <param name="WebForm">The web form.</param>
    /// <param name="FileNameWhenUserDownload">The file name when user download.</param>
    public static void AlertMessageToClientFile(System.Web.UI.Page WebForm, string FileNameWhenUserDownload)
    {

        //byte[] Exception = Encoding.Default.GetBytes(GetResultSendMessage());
        //MemoryStream ms = new MemoryStream(Exception);
        //return ms;
        DownloadFile(WebForm, FileNameWhenUserDownload, GetResultSendMessage());

    }
    /// <summary>
    /// 將訊息在存在指定主機端Log檔.
    /// </summary>
    /// <param name="FileName">Name of the file.</param>
    public static void AlertMessageToLogFile(string FileName)
    {
        byte[] Exception = Encoding.Default.GetBytes(GetResultSendMessage());
        FileStream fs;
        //if (LogFileName != string.Empty)
        //    fs = new FileStream(LogFileName, FileMode.Append, FileAccess.Write);
        //else
            fs = new FileStream(FileName, FileMode.Append, FileAccess.Write);
        fs.Write(Exception, 0, Exception.Length);
        fs.Flush();
        fs.Close();
    }
    /// <summary>
    /// 將訊息在存在預設主機端Log檔.
    /// </summary>
    /// <param name="WebForm">The web form.</param>
    public static void AlertMessageToLogFile(System.Web.UI.Page WebForm)
    {        
        byte[] Exception = Encoding.Default.GetBytes(GetResultSendMessage());
        FileStream fs;
        if (LogFileName != string.Empty)
            fs = new FileStream(LogFileName, FileMode.Append, FileAccess.Write);
        else
            fs = new FileStream(WebForm.Server.MapPath("./")+ LogFileNameByDate , FileMode.Append, FileAccess.Write);
        fs.Write(Exception, 0, Exception.Length);
        fs.Flush();
        fs.Close();
    }
    /// <summary>
    /// 將訊息寄出到預設電子郵件.
    /// </summary>
    public static void AlertMessageToEmail()
    {

        foreach (string temp in DealerEMail)
        {
            string result = "您好:\r\n本信件由系統發出,請勿回信謝謝!\r\n" + GetResultSendMessage();
            SendMail(SenderMail, temp, "系統錯誤", result);
        }
    }
    /// <summary>
    /// 將訊息寄出到指定電子郵件.
    /// </summary>
    /// <param name="ReceiverEMail">The receiver E mail.</param>
    public static void AlertMessageToEmail(string[] RecieverEMail)
    {

        foreach (string temp in RecieverEMail)
        {
            string result = "您好:\r\n本信件由系統發出,請勿回信謝謝!\r\n" + GetResultSendMessage();
            SendMail(SenderMail, temp, "系統錯誤", result);
        }
    }

    /// <summary>
    /// 將訊息寫入DB,表格名稱為系統名+Log.
    /// </summary>
    /// <param name="ConnectString">The connect string.</param>
    /// <param name="SystemName">Name of the system.</param>
    /// <param name="MType">Type of the M.</param>
    /// <param name="Message">The message.</param>
    public static void AlertMessageToDB(string ConnectString ,string SystemName,MessageType MType, string Message)
    {
        string SqlCmd = InsertTable(SystemName, MType, Message);
        using(SqlConnection cn = new SqlConnection(ConnectString))
        {
            cn.Open();
            using(SqlCommand cmd = new SqlCommand(SqlCmd,cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
    }
    /// <summary>
    /// 將訊息寫入DB,表格名稱為系統名+Log.
    /// </summary>
    /// <param name="ConnectString">The connect string.</param>
    /// <param name="SystemName">Name of the system.</param>
    /// <param name="MType">Type of the M.</param>
    /// <param name="Message">The message.</param>
    public static void AlertMessageToDB(string ConnectString, string SystemName)
    {
        string SqlCmd = InsertTable(SystemName, ErrorType, ErrorMessage);
        using (SqlConnection cn = new SqlConnection(ConnectString))
        {
            cn.Open();
            using (SqlCommand cmd = new SqlCommand(SqlCmd, cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
    }
    
    #endregion
    #region 送郵件
    /// <summary>
    /// 利用伺服器SMTP寄送郵件
    /// 
    /// </summary>
    /// <param name="MailServer">The mail server.</param>
    /// <param name="Account">The account.</param>
    /// <param name="Password">The password.</param>
    /// <param name="FromMailAddress">From mail address.</param>
    /// <param name="toMailAddress">To mail address.</param>
    /// <param name="subject">The subject.</param>
    /// <param name="body">The body.</param>
    public static void SendMail(string FromMailAddress, string toMailAddress, string subject, string body)
    {

        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("LocalHost");
        //指定 Smtp 伺服器
        smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        //指定外送電子郵件的處理方式
        smtp.Credentials = new System.Net.NetworkCredential("", "");
        //利用帳號/密碼取得 Smtp 伺服器的憑證
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        //要發送的訊息
        msg.SubjectEncoding = System.Text.Encoding.Default;
        //主旨的編碼方式
        msg.BodyEncoding = System.Text.Encoding.Default;
        //訊息主體(郵件內容)的編碼方式
        msg.IsBodyHtml = false;
        //訊息主體(郵件內容)不要以 HTML 的方式呈現
        msg.From = new System.Net.Mail.MailAddress(FromMailAddress);
        //寄件者
        msg.To.Add(new System.Net.Mail.MailAddress(toMailAddress));
        //收件者
        msg.Subject = subject;
        //主旨
        msg.Body = body;
        //訊息主體(郵件內容)
        smtp.Send(msg);
        //發送 e-mail
        msg.Dispose();
        //釋放訊息所佔用的記憶體
    }
    #endregion
    #region 網頁下載
    /// <summary>
    /// 將主機端文件下載.
    /// </summary>
    /// <param name="WebForm">The web form.</param>
    /// <param name="FileNameWhenUserDownload">The file name when user download.</param>
    /// <param name="FilePath">The file path.</param>
    public static void DownloadFileFromServer(System.Web.UI.Page WebForm, string FileNameWhenUserDownload, string FilePath)
    {
        WebForm.Response.ClearHeaders();
        WebForm.Response.Clear();
        WebForm.Response.Expires = 0;
        WebForm.Response.Buffer = true;
        WebForm.Response.AddHeader("Accept-Language", "zh-tw");
        //檔案名稱
        WebForm.Response.AddHeader("content-disposition", "attachment; filename=" + FileNameWhenUserDownload);
        WebForm.Response.ContentType = "Application/octet-stream";
        //檔案內容
        FileInfo fi = new FileInfo(FilePath);
        string Reuslt = string.Empty;
        if (fi.Extension == "xml")
            Reuslt = Encoding.UTF8.GetString(System.IO.File.ReadAllBytes(FilePath));
        else
            Reuslt = Encoding.Default.GetString(System.IO.File.ReadAllBytes(FilePath));
        WebForm.Response.Write(Reuslt);
        WebForm.Response.End();
    }
    /// <summary>
    /// 將客戶端產生文件下載.
    /// </summary>
    /// <param name="WebForm">The web form.</param>
    /// <param name="FileNameWhenUserDownload">The file name when user download.</param>
    /// <param name="FileBody">The file body.</param>
    public static void DownloadFile(System.Web.UI.Page WebForm, string FileNameWhenUserDownload, string FileBody)
    {
        WebForm.Response.ClearHeaders();
        WebForm.Response.Clear();
        WebForm.Response.Expires = 0;
        WebForm.Response.Buffer = true;
        WebForm.Response.AddHeader("Accept-Language", "zh-tw");
        //檔案名稱
        WebForm.Response.AddHeader("content-disposition", "attachment; filename=" + FileNameWhenUserDownload);
        WebForm.Response.ContentType = "Application/octet-stream";
        //檔案內容        
        WebForm.Response.Write(FileBody);
        WebForm.Response.End();
    }
    #endregion
    #region sql指令區
    /// <summary>
    /// 建立訊息表格,表格名稱為系統名+Log.
    /// </summary>
    /// <param name="ConnectString">The connect string.</param>
    /// <param name="SystemName">Name of the system.</param>
    public static void CreateMessageTable(string ConnectString, string SystemName)
    {
        string SqlCmd = CreateTable(SystemName);
        using (SqlConnection cn = new SqlConnection(ConnectString))
        {
            cn.Open();
            using (SqlCommand cmd = new SqlCommand(SqlCmd, cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
    }
    /// <summary>
    /// Creates the table.
    /// </summary>
    /// <param name="SystemName">Name of the system.</param>
    /// <returns></returns>
    public static string CreateTable(string SystemName)
    {
        return " CREATE TABLE ["+ SystemName +"Log]("
	    + " [MessageIndex] [int] IDENTITY(1,1) NOT NULL, "
	    +" [MessageType] [varchar](4)  NULL, "
	    +" [MessageContent] [text] NULL, "
	    +" [RecordDate] [datetime] NULL CONSTRAINT [DF_"+SystemName+"_RecordDate]  DEFAULT (getdate())) ";    
    }
    /// <summary>
    /// Drops the table.
    /// </summary>
    /// <param name="SystemName">Name of the system.</param>
    /// <returns></returns>
    public static string DropTable(string SystemName)
    {
        return " drop table " + SystemName + "Log";
    }
    /// <summary>
    /// Inserts the table.
    /// </summary>
    /// <param name="SystemName">Name of the system.</param>
    /// <param name="MType">Type of the M.</param>
    /// <param name="MContent">Content of the M.</param>
    /// <returns></returns>
    public static string InsertTable(string SystemName, MessageType MType, string MContent)
    {
        return " INSERT INTO " + SystemName + "Log ( MessageType, MessageContent)"
                + " VALUES     ('"+MType.ToString()+"', '" + MContent.Replace("'",";").ToString() + "')";
    }    
    #endregion

}