using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;

namespace eFrameWork
{
    public partial class Global : System.Web.HttpApplication
    {
        protected void Application_PreSendRequestHeaders()
        {
            Response.Headers["Server"] = "WWWServer"; //集成模式下有效
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            if (Context != null)
            {
                HttpContext ctx = HttpContext.Current;
                Exception ex = ctx.Server.GetLastError();
                HttpException ev = ex as HttpException;
                if (ev != null)
                {
                    string dir = HttpContext.Current.Server.MapPath("~/Error/log/");
                    if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
                    StringBuilder sb = new StringBuilder();
                    string err = ex.ToString();
                    sb.Append("URL:" + HttpContext.Current.Request.RawUrl + "\r\n");
                    sb.Append("User-Agent:" + HttpUtility.UrlDecode(this.Request.UserAgent) + "\r\n");
                    sb.Append("Form:" + HttpUtility.UrlDecode(this.Request.Form.ToString()) + "\r\n");
                    sb.Append("Cookies:" + HttpUtility.UrlDecode(this.Request.Form.ToString()) + "\r\n");


                    string error = eBase.getCenterString(err, " ---> ", "\r\n");
                    error = eBase.getRightString(error, ": ");
                    string line = eBase.getCenterString(err, "行号 ", "\r\n");

                    sb.Append("HttpCode:" + ev.GetHttpCode() + "\r\n");
                    sb.Append("Error:" + error + "\r\n");
                    sb.Append("Line:" + line + "\r\n");
                    sb.Append("Message:\r\n" + ex.ToString() + "\r\n");

                    eBase.AppendLog("~/Error/log/" + string.Format("{0:yyyy_MM_dd}", DateTime.Now) + ".log", sb.ToString());

                    //Exception exp = ex.GetBaseException();
                    if (ev.GetHttpCode() == 404)
                    {
                        ctx.ClearError();
                        string path = Server.MapPath("~/Error/404.html");
                        if (System.IO.File.Exists(path))
                        {
                            string html = eBase.ReadFile(path);
                            Response.Write(html);
                            Response.End();
                        }

                    }
                    if (ev.GetHttpCode() == 500)
                    {
                        ctx.ClearError();
                        string path = Server.MapPath("~/Error/500.html");
                        if (System.IO.File.Exists(path))
                        {
                            string html = eBase.ReadFile(path);
                            Response.Write(html);
                            Response.End();
                        }
                        Response.End();
                    }



                    Server.ClearError();
                    Response.Clear();
                    Response.ContentType = "text/html; charset=utf-8";
                    Response.Write(ev.GetHttpCode() + "::" + error);
                    Response.End();
                }
            }
        }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (eConfig.Debug()) eBase.Writeln("BeginRequest");
            //Response.ContentType = "text/html; charset=utf-8";
            //Response.Write("本站暂停访问!稍后重试。");
            //Response.End(); 

            //string accUrl = eConfig.AccessorysURL();
            


            Application["StartTime"] = System.DateTime.Now;
        }
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            if (eConfig.Debug()) eBase.Writeln("EndRequest");

            return;

            System.DateTime startTime = (System.DateTime)Application["StartTime"];
            System.DateTime endTime = System.DateTime.Now;
            System.TimeSpan ts = endTime - startTime;
            //Response.Write("<br>页面执行时间:" + ts.Milliseconds + " 毫秒"); //测试完指定页面后请注释，否则影响有些输出结果(如：json)
        }

        private void msg()
        {
            msg("请勿非法提交!");
        }
        private void msg(string str)
        {
            Response.ContentType = "text/html; charset=utf-8";
            Response.Write("<script>alert('" + str + "');history.back();<" + @"/" + "script>");
            Response.End();
        }

        private bool ProcessSqlStr(string key, string value, int type)
        {
            if (value.Length == 0) { return true; }
            string keys;
            if (type == 0) //QueryString
            {
                keys = "'|exists| and |exec|insert |select |delete |update |count|*|chr|mid|master|truncate |char|declare |script|=|\"|;|onmouse|onkey|<|>|benchmark|waitfor|delay|.log|.ini|ddbms_pipe.receive_message|information_schema|";
            }
            else //Form
            {
                //SqlStr = "'|exec |insert |select |delete |update |count |chr|mid|master |truncate |char |declare |and |script";
                keys = "exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare |and |script";
            }
            bool back = true;
            try
            {
                string[] arrs = keys.Split('|');
                foreach (string str in arrs)
                {
                    if (str.Length > 0 && value.ToLower().IndexOf(str) > -1)
                    {
                        back = false;
                    }
                }
            }
            catch
            {
                back = false;
            }
            return back;
        }
    }
}