構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的後臺管理系統(12)-系統日誌和異常的處理②

系列目錄javascript

上一講咱們作了日誌與異常的結果顯示列表,這一節咱們講要把他應用系統中來。html

首先咱們在App.Common類庫中建立一個通用類ResultHelper,這個類裏面寫了,獲取一個GUID,獲取當前時間,處理字符串等操做,雖然咱們目前要用到的一個就是獲取GUID可是之後咱們可能還要用到別的,因此我都把他放進入了java

而後在App.Admin建立一個核心文件夾,Core,放入LogHandler這個類是主要是寫入日誌,避免在每次都要實例化這個類,我把他封裝起來,你們一看就知道。ajax

而後修改Controller的Create方法,代碼以下一一給出。sql

using System;
using System.Web;
using System.Text.RegularExpressions;

namespace App.Common
{
    public class ResultHelper
    {
        /// <summary>
        /// 建立一個全球惟一的32位ID
        /// </summary>
        /// <returns>ID串</returns>
        public static string NewId
        {
            get
            {
                string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                string guid = Guid.NewGuid().ToString().Replace("-", "");
                id += guid.Substring(0, 10);
                return id;
            }
        }
        public static string NewTimeId
        {
            get
            {
                string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                return id;
            }
        }
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="value">字符串</param>
        /// <param name="length">剩下長度</param>
        /// <returns>指定字符串並加...</returns>
        public static string SubValue(string value, int length)
        {
            if (value.Length > length)
            {
                value = value.Substring(0, length); value = value + "..."; return NoHtml(value);
            }
            else { return NoHtml(value); }
        }
        //還原的時候
        public static string InputText(string inputString)
        {

            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();
                //if (inputString.Length > maxLength) 
                //inputString = inputString.Substring(0, maxLength); 
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("&", "&amp");
                inputString = inputString.Replace("'", "''");
                inputString = inputString.Replace("<", "&lt");
                inputString = inputString.Replace(">", "&gt");
                inputString = inputString.Replace("chr(60)", "&lt");
                inputString = inputString.Replace("chr(37)", "&gt");
                inputString = inputString.Replace("\"", "&quot");
                inputString = inputString.Replace(";", ";");

                return inputString;
            }
            else
            {
                return "";
            }

        }
        //添加的時候
        public static string OutputText(string outputString)
        {

            if ((outputString != null) && (outputString != String.Empty))
            {
                outputString = outputString.Trim();
                outputString = outputString.Replace("&amp", "&");
                outputString = outputString.Replace("''", "'");
                outputString = outputString.Replace("&lt", "<");
                outputString = outputString.Replace("&gt", ">");
                outputString = outputString.Replace("&lt", "chr(60)");
                outputString = outputString.Replace("&gt", "chr(37)");
                outputString = outputString.Replace("&quot", "\"");
                outputString = outputString.Replace(";", ";");
                outputString = outputString.Replace("\n", "<br>");
                return outputString;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 去除HTML標記
        /// </summary>
        /// <param name="NoHTML">包括HTML的源碼 </param>
        /// <returns>已經去除後的文字</returns>
        public static string NoHtml(string Htmlstring)
        {
            //刪除腳本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //刪除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;

        }
        /// <summary>
        /// 格式化文本(防止SQL注入)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Formatstr(string html)
        {
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //過濾<script></script>標記
            html = regex2.Replace(html, ""); //過濾href=javascript: (<A>) 屬性
            html = regex3.Replace(html, " _disibledevent="); //過濾其它控件的on...事件
            html = regex4.Replace(html, ""); //過濾iframe
            html = regex10.Replace(html, "s_elect");
            html = regex11.Replace(html, "u_pudate");
            html = regex12.Replace(html, "d_elete");
            html = html.Replace("'", "");
            html = html.Replace("&nbsp;", " ");
            return html;
        }
        /// <summary>
        /// 檢查SQL語句合法性
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool ValidateSQL(string sql, ref string msg)
        {
            if (sql.ToLower().IndexOf("delete") > 0)
            {
                msg = "查詢參數中含有非法語句DELETE";
                return false;
            }
            if (sql.ToLower().IndexOf("update") > 0)
            {
                msg = "查詢參數中含有非法語句UPDATE";
                return false;
            }

            if (sql.ToLower().IndexOf("insert") > 0)
            {
                msg = "查詢參數中含有非法語句INSERT";
                return false;
            }
            return true;
        }
        //獲取當前時間
        public static DateTime NowTime
        {
            get 
            {
                return DateTime.Now;
            }
        }

        /// <summary>
        /// 將日期轉換成字符串
        /// </summary>
        /// <param name="dt">日期</param>
        /// <returns>字符串</returns>
        public static string DateTimeConvertString(DateTime? dt)
        {
            if (dt == null)
            {
                return "";
            }
            else
            {
                return Convert.ToDateTime(dt.ToString()).ToShortDateString();
            }
        }
        /// <summary>
        /// 將字符串轉換成日期
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>日期</returns>
        public static DateTime? StringConvertDatetime(string str)
        {
            if (str == null)
            {
                return null ;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(str);
                }
                catch {
                    return null;
                }
            }
        }

        public static string GetUserIP()
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
            else
                return System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
    }
}
ResultHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Common;
using App.DAL;
using App.IBLL;
using App.Models;
using Microsoft.Practices.Unity;

namespace App.Admin
{
    public static class LogHandler
    {
        [Dependency]
        public static ISysLogBLL logBLL { get; set; }
        /// <summary>
        /// 寫入日誌
        /// </summary>
        /// <param name="oper">操做人</param>
        /// <param name="mes">操做信息</param>
        /// <param name="result">結果</param>
        /// <param name="type">類型</param>
        /// <param name="module">操做模塊</param>
        public static void WriteServiceLog(string oper, string mes, string result, string type, string module)
        {
           
               
                SysLog entity = new SysLog();
                entity.Id = ResultHelper.NewId;
                entity.Operator = oper;
                entity.Message = mes;
                entity.Result = result;
                entity.Type = type;
                entity.Module = module;
                entity.CreateTime = ResultHelper.NowTime;
                using (SysLogRepository logRepository = new SysLogRepository())
                {
                    logRepository.Create(entity);
                }
        
        }
    }
}
LogHandler
 [HttpPost]
        public JsonResult Create(SysSampleModel model)
        {


                if (m_BLL.Create(model))
                {
                    LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name, "成功", "建立", "樣例程序");
                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name, "失敗", "建立", "樣例程序");
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
     
        }
SysSampleController

同時App.Common要引用程序集System.Webjson

運行添加一條記錄,而後打開咱們的日誌模塊,OK,日誌記錄完成了,有點簡單。ide

接下來是異常,上一講說到,異常咱們放在BLL中處理,而後咱們把錯誤或者異常信息返回到Controller中被日誌記錄,固然異常他是在BLL層被記錄的。網站

咱們須要一個異常的集合類,來記錄BLL層和DAL層,有時候DAL也要處理異常,因此咱們也要用到ref 引用傳遞,貌似ref咱們很喜歡,呵呵ui

見代碼,在App.Common建立一個異常集合類this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Common
{
    public class ValidationError
    {
        public ValidationError() { }
        public string ErrorMessage { get; set; }
       
    }
    public class ValidationErrors : List<ValidationError>
    {
        /// <summary>
        /// 添加錯誤
        /// </summary>
        /// <param name="errorMessage">信息描述</param>
        public void Add(string errorMessage)
        {
            base.Add(new ValidationError { ErrorMessage = errorMessage });
        }
        /// <summary>
        /// 獲取錯誤集合
        /// </summary>
        public string Error
        {
            get {
                string error = "";
                this.All(a => {
                    error += a.ErrorMessage;
                    return true;
                });
                return error;
            } 
        }
    }
}
ValidationErrorHelper.cs

咱們也要建立一個封裝好的異常寫入,相似與Log的LogHandler封裝但咱們放在BLL中,由於咱們之後的其餘項目的BLL要引用,這一步要考慮到。
在BLL中建立文件夾Core,寫入如下類,BLL引用程序集System.Web裏面用到了http的一些方法

using System;
using System.Web.Configuration;
using App.Models;
using System.IO;
using System.Text;
using App.Common;

namespace App.BLL.Core
{

        /// <summary>
        /// 寫入一個異常錯誤
        /// </summary>
        /// <param name="ex">異常</param>
        public static class ExceptionHander
        {
            /// <summary>
            /// 加入異常日誌
            /// </summary>
            /// <param name="ex">異常</param>
            public static void WriteException(Exception ex)
            {
               
                    try
                    {
                        using (DBContainer db = new DBContainer())
                        {
                            SysException model = new SysException()
                            {
                                Id = ResultHelper.NewId,
                                HelpLink = ex.HelpLink,
                                Message = ex.Message,
                                Source = ex.Source,
                                StackTrace = ex.StackTrace,
                                TargetSite = ex.TargetSite.ToString(),
                                Data =ex.Data.ToString(),
                                CreateTime = ResultHelper.NowTime
                                
                            };
                            db.SysException.AddObject(model);
                            db.SaveChanges();
                        }
                    }
                    catch (Exception ep)
                    {
                        try
                        {
                            //異常失敗寫入txt
                            string path = @"~/exceptionLog.txt";
                            string txtPath = System.Web.HttpContext.Current.Server.MapPath(path);//獲取絕對路徑
                            using (StreamWriter sw = new StreamWriter(txtPath, true, Encoding.Default))
                            {
                                sw.WriteLine((ex.Message + "|" + ex.StackTrace + "|" + ep.Message + "|" + DateTime.Now.ToString()).ToString());
                                sw.Dispose();
                                sw.Close();
                            }
                            return;
                        }
                        catch { return; }
                    }

                

            }
        }

    
}
ExceptionHander

此異常當處理也異常時候,將在網站根目錄下寫入一個txt文件。
建立一個全局變量

ValidationErrors errors = new ValidationErrors();

咱們要用引用傳遞,因此要修改IBLL和BLL的Create方法,以下
ISysSampleBLL  :  bool Create(ref ValidationErrors errors, SysSampleModel model);

SysSampleBLL   :

 /// <summary>
        /// 建立一個實體
        /// </summary>
        /// <param name="errors">持久的錯誤信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        /// <summary>
        /// 建立一個實體
        /// </summary>
        /// <param name="errors">持久的錯誤信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        public bool Create(ref ValidationErrors errors, SysSampleModel model)
        {
            try
            {
                SysSample entity = Rep.GetById(model.Id);
                if (entity != null)
                {
                    errors.Add("主鍵重複");
                    return false;
                }
                entity = new SysSample();
                entity.Id = model.Id;
                entity.Name = model.Name;
                entity.Age = model.Age;
                entity.Bir = model.Bir;
                entity.Photo = model.Photo;
                entity.Note = model.Note;
                entity.CreateTime = model.CreateTime;

                if (Rep.Create(entity) == 1)
                {
                    return true;
                }
                else
                {
                    errors.Add("插入失敗");
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

修改Controller

 [HttpPost]
        public JsonResult Create(SysSampleModel model)
        {
                if (m_BLL.Create(ref errors, model))
                {
                    LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name, "成功", "建立", "樣例程序");
                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name + "," + ErrorCol, "失敗", "建立", "樣例程序");
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
     
        }

 注意:ExceptionHander.WriteException(ex);這裏是寫入異常信息

OK,你如今能夠建立一條新的記錄和插入一個ID大於50個字符的記錄,讓他記錄日誌和異常了。

顯然咱們的失敗錯誤提示已經不符合國情了。咱們返回的json格式是0和1咱們要返回多個值了,好比1和成功建立,0和失敗了啊,這樣的2個值怎麼辦?

controller能把datagrid傳過來的東西用類來接受,那麼反過來想,js也能把controller發出去的值分解,建立一個序列化的類

在App.Common類庫中建立JsonHandler幫助類,裏面有2個重載,一個是返回3個值一個是2個值的。

因此當咱們要返回訂單的數量和總價格的時候,咱們將用到相似的手段

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Common
{
    public class JsonHandler
    {

        public static JsonMessage CreateMessage(int ptype,string pmessage,string pvalue)
        {
            JsonMessage json = new JsonMessage()
            {
                type = ptype,
                message = pmessage,
                value = pvalue
            };
            return json;
        }
        public static JsonMessage CreateMessage(int ptype, string pmessage)
        {
            JsonMessage json = new JsonMessage()
            {
                type = ptype,
                message = pmessage,
            };
            return json;
        }
    }

    public class JsonMessage
    {
        public int type{get;set;}
        public string message{get;set;}
        public string value{get;set;}
    }
}
JsonHandler

再次修改Controller的Create

  [HttpPost]
        public JsonResult Create(SysSampleModel model)
        {
            if (m_BLL.Create(ref errors, model))
            {
                LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name, "成功", "建立", "樣例程序");
                return Json(JsonHandler.CreateMessage(1, "插入成功"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog("虛擬用戶", "Id:" + model.Id + ",Name:" + model.Name + "," + ErrorCol, "失敗", "建立", "樣例程序");
                return Json(JsonHandler.CreateMessage(0, "插入失敗" + ErrorCol), JsonRequestBehavior.AllowGet);
            }
     
        }

修改SysSample的Create的JS部分

<script type="text/javascript">
    $(function () {
        $("#btnSave").click(function () {
            if ($("#CreateForm").valid()) {
                $.ajax({
                    url: "/SysSample/Create",
                    type: "Post",
                    data: $("#CreateForm").serialize(),
                    dataType: "json",
                    success: function (data) {
                        if (data.type == 1) {
                            window.parent.frameReturnByMes(data.message);
                            window.parent.frameReturnByReload(true);
                            window.parent.frameReturnByClose()
                        }
                        else {
                            window.parent.frameReturnByMes(data.message);
                        }
                    }
                });
            }
            return false;
        });
    });
    </script>

 

因爲時間關係,這一講就先到這裏吧!這一講其實比較倉促。不懂的留言

你須要繼續作的就是在刪除,編輯等操做也加入這些的。這點留給你們本身表現吧....

下一講是全局異常的捕獲。

相關文章
相關標籤/搜索