using System;
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.Data.SqlClient;
using System.Windows.Forms;
using System.Text;
using System.IO;

public class Cls_Operation
{
    //定义变量
    public SqlConnection Conn;
    public SqlConnection Conn_Child;

    //打开主数据库
    public void OpenConn()
    {
        if (this.Conn == null)
        {
            this.Conn = new SqlConnection("server=h30.dgasp.com;database=WTODataMaster;user id=WTODataMaster;pwd=wto168.com;");
        }
        if (this.Conn.State == ConnectionState.Closed)
        {
            this.Conn.Open();
        }
    }

    //关闭主数据库
    public void CloseConn()
    {
        if (this.Conn != null)
        {
            this.Conn.Close();
        }
    }

    //执行主数据库的SQL语句
    public bool ExecSql(string strSql)
    {
        try
        {
            OpenConn();
            SqlCommand Cmd = new SqlCommand(strSql, Conn);
            Cmd.ExecuteNonQuery();
            Cmd.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            CloseConn(); 
        }
    }

    //打开子数据库
    public void OpenConn_Child()
    {
        if (this.Conn_Child == null)
        {
            this.Conn_Child = new SqlConnection(ConfigurationManager.AppSettings["Custmerconn"].ToString());
        }
        if (this.Conn_Child.State == ConnectionState.Closed)
        {
            this.Conn_Child.Open();
        }
    }

    //关闭子数据库
    public void CloseConn_Child()
    {
        if (this.Conn_Child != null)
        {
            this.Conn_Child.Close();
        }
    }

    //执行子数据库的SQL语句
    public bool ExecSql_Child(string strSql)
    {
        try
        {
            OpenConn_Child();
            SqlCommand Cmd = new SqlCommand(strSql, Conn_Child);
            Cmd.ExecuteNonQuery();
            Cmd.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    public string GetRecord_Child(string strSql)
    {
        try
        {
            OpenConn_Child();
            SqlCommand Cmd = new SqlCommand(strSql, Conn_Child);
            string sResult = Convert.ToString(Cmd.ExecuteScalar());
            Cmd.Dispose();
            return sResult;
        }
        catch
        {
            return null;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    public int GetRecordCount_Child(string strSql)
    {
        try
        {
            OpenConn_Child();
            SqlCommand Cmd = new SqlCommand(strSql, Conn_Child);
            int iCount = Convert.ToInt32(Cmd.ExecuteScalar());
            Cmd.Dispose();
            return iCount;
        }
        catch
        {
            return 0;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    public int GetRowsCount_Child(string strSql)
    {
        try
        {
            int iCount = 0;
            OpenConn_Child();
            SqlCommand Cmd = new SqlCommand(strSql, Conn_Child);
            SqlDataReader dataReader = Cmd.ExecuteReader();
            while (dataReader.Read())
            {
                iCount += Convert.ToInt32(dataReader[0]);
            }
            dataReader.Close();
            Cmd.Dispose();
            return iCount;
        }
        catch
        {
            return 0;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    public int GetColsCount_Child(string strSql)
    {
        try
        {
            int iCount = 0;
            OpenConn_Child();
            SqlCommand Cmd = new SqlCommand(strSql, Conn_Child);
            SqlDataReader dataReader = Cmd.ExecuteReader();
            while (dataReader.Read())
            {
                iCount += 1;
            }
            dataReader.Close();
            Cmd.Dispose();
            return iCount;
        }
        catch
        {
            return 0;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    public DataSet GetDataSet_Child(string strSql, string sDSName)
    {
        try
        {
            OpenConn_Child();
            DataSet dataSet = new DataSet();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, Conn_Child);
            dataAdapter.Fill(dataSet, sDSName);
            dataAdapter.Dispose();
            return dataSet;
        }
        catch
        {
            return null;
        }
        finally
        {
            CloseConn_Child();
        }
    }

    //获取IP地址
    public string GetIP()
    {
        string sIp = null;
        if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        {
            sIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
        }
        else
        {
            sIp = HttpContext.Current.Request.UserHostAddress;
        }
        if (sIp.Contains("::1"))
        {
            sIp = "127.0.0.1";
        }
        return sIp;
    }

    //获取IP所在地区
    public string GetArea()
    {
        try
        {
            long ip = Convert.ToInt64(GetIP().Replace(".", ""));
            this.OpenConn();
            SqlCommand smd = new SqlCommand("select address from ip where cast(ips as bigint) < " + ip + " and cast(ipe as bigint) > " + ip + "", this.Conn);
            string area = Convert.ToString(smd.ExecuteScalar());
            this.CloseConn();
            area = area.Replace("CZ88.NET", "");
            area = area.Replace(" ", "");
            if (area == "IANA" || area == "") { area = "Unknown ipaddress"; }
            if (ip == 127001) { area = "Local ipaddress"; }
            return area;
        }
        catch
        {
            return ("");
        }
    }

    //获取来源网址
    public string GetSourceUrl()
    {
        string sUrl = null;
        if (HttpContext.Current.Request.ServerVariables["HTTP_REFERER"] != null)
        {
            sUrl = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            if (sUrl != "" && sUrl.Substring(sUrl.Length - 1, 1) == "/")
            {
                sUrl = sUrl.Substring(0, sUrl.Length - 1);
            }
        }
        else
        {
            sUrl = "直接输入";
        }
        return sUrl;
    }

    //获取访问网址
    public string GetVisitUrl()
    {
        string sUrl = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() + HttpContext.Current.Request.ServerVariables["URL"].ToString();
        if (sUrl != "" && sUrl.Substring(sUrl.Length - 1, 1) == "/")
        {
            sUrl = sUrl.Substring(0, sUrl.Length - 1);
        }
        return sUrl;
    }

    //获取当前网址(不包含域名部分)
    public string GetServerName()
    {
        string strUrl = HttpContext.Current.Request.ServerVariables["URL"];
        string sUrl = "";
        if (strUrl.StartsWith("/"))
        {
            string[] Url = strUrl.Split('/');
            for (int i = 1; i < Url.Length; i++)
            {
                sUrl += Url[i];
            }
        }
        return sUrl;
    }

    //获取显示器分辨率
    public string GetResolution()
    {
        return Screen.PrimaryScreen.Bounds.Width.ToString() + "×" + Screen.PrimaryScreen.Bounds.Height.ToString();
    }

    //获取操作系统
    public string GetOS()
    {
        string os = null;
        string sAgentInfo = HttpContext.Current.Request.UserAgent.ToString();
        if (sAgentInfo.Contains("Windows NT 6.0"))
        {
            os = "Windows Vista";
        }
        else if (sAgentInfo.Contains("Windows NT 5.2"))
        {
            os = "Windows 2003";
        }
        else if (sAgentInfo.Contains("Windows NT 5.1"))
        {
            os = "Windows XP";
        }
        else if (sAgentInfo.Contains("Windows NT 5"))
        {
            os = "Windows 2000";
        }
        else if (sAgentInfo.Contains("Win 9x 4.90"))
        {
            os = "Windows ME";
        }
        else if (sAgentInfo.Contains("Windows CE"))
        {
            os = "Windows CE";
        }
        else if (sAgentInfo.Contains("Windows NT 98"))
        {
            os = "Windows 98";
        }
        else if (sAgentInfo.Contains("Windows NT 95"))
        {
            os = "Windows 95";
        }
        else if (sAgentInfo.Contains("Mac"))
        {
            os = "Mac";
        }
        else if (sAgentInfo.Contains("Unix") || sAgentInfo.Contains("SunOS") || sAgentInfo.Contains("BSD"))
        {
            os = "Unix";
        }
        else if (sAgentInfo.Contains("Linux"))
        {
            os = "Linux";
        }
        else
        {
            os = "Other OS";
        }
        return os;
    }

    //获取浏览器
    public string GetBrowser()
    {
        string browser = null;
        string sAgentInfo = HttpContext.Current.Request.UserAgent.ToString();
        if (sAgentInfo.Contains("MSIE 7"))
        {
            browser = "MSIE 7.0";
        }
        else if (sAgentInfo.Contains("MSIE 6"))
        {
            browser = "MSIE 6.0";
        }
        else if (sAgentInfo.Contains("MSIE 5"))
        {
            browser = "MSIE 5.0";
        }
        else if (sAgentInfo.Contains("MSIE 4"))
        {
            browser = "MSIE 4.0";
        }
        else if (sAgentInfo.Contains("Netscape"))
        {
            browser = "Netscape";
        }
        else if (sAgentInfo.Contains("Opera"))
        {
            browser = "Opera";
        }
        else
        {
            browser = "Other Browser";
        }
        return browser;
    }

    //获取系统语言
    public string GetLanguage()
    {
        string sLan;
        HttpRequest request = HttpContext.Current.Request;
        sLan = request.UserLanguages[0];
        return sLan;
    }

    //获取指定长度的随机数
    public string GetRandNumber(int iLength, string sType)
    {
        Random random = new Random(unchecked((int)DateTime.Now.Ticks));
        StringBuilder stringbuilder = new StringBuilder(iLength);
        for (int i = 0; i < iLength; i++)
        {
            stringbuilder.Append(random.Next(0, 9));
        }
        switch (sType)
        {
            case "NUM":
                return stringbuilder.ToString();
            case "DATE":
                return GetDateTime() + stringbuilder.ToString();
            default:
                return stringbuilder.ToString();
        }
    }

    //获取格式化后的当前系统时间
    public string GetDateTime()
    {
        return (((DateTime.Now.ToString().Replace("/", "")).Replace("-", "")).Replace(":", "")).Replace(" ", "");
    }

    //截取字符串
    public string Cutstring(string sStr, int iLen)
    {
        byte[] sArray = Encoding.Default.GetBytes(sStr);
        if (sArray.Length > iLen)
        {
            return Encoding.Default.GetString(sArray, 0, iLen) + "...";
        }
        else
        {
            return sStr;
        }
    }

    //获取两个时间的差值
    public int DateDif(DateTime DateTime1, DateTime DateTime2, string sType)
    {
        int dateDiff = 0;
        TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
        TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
        TimeSpan ts = ts1.Subtract(ts2).Duration();
        switch (sType.ToLower())
        {
            case "hour":
                dateDiff = ts.Hours;
                break;
            case "minute":
                dateDiff = ts.Minutes;
                break;
            case "second":
                dateDiff = ts.Seconds;
                break;
        }
        return dateDiff;
    }

    public double DateDiff(DateTime DateTime1, DateTime DateTime2, string sType)
    {
        double datediff = 0;
        TimeSpan ts = new TimeSpan(DateTime2.Ticks - DateTime1.Ticks);
        switch (sType.ToLower())
        {
            case "year":
                datediff = Convert.ToDouble(ts.TotalDays / 365);
                break;
            case "month":
                datediff = Convert.ToDouble((ts.TotalDays / 365) * 12);
                break;
            case "day":
                datediff = Convert.ToDouble(ts.TotalDays);
                break;
            case "hour":
                datediff = Convert.ToDouble(ts.TotalHours);
                break;
            case "minute":
                datediff = Convert.ToDouble(ts.TotalMinutes);
                break;
            case "second":
                datediff = Convert.ToDouble(ts.TotalSeconds);
                break;
        }
        return datediff;
    }

    //重写文件
    public void WriteFile(string sFileName, string sFileContent)
    {
        if (!File.Exists(sFileName))
        {
            File.Create(sFileName, 1).Close();
        }
        StreamWriter sw = new StreamWriter(sFileName);
        sw.Write(sFileContent);
        sw.Close();
    }

    //保存系统安全日志
    public bool SaveLog(string sLog)
    {
        string[] objArray = HttpContext.Current.Request.ServerVariables["URL"].ToString().Split('/');
        string sOperator = HttpContext.Current.Session["UserName_Back"].ToString();
        if (this.ExecSql("Insert Into Sys_Log (L_Operator,L_Object,L_Content,L_Date,L_Ip) Values('" + sOperator + "','" + objArray[objArray.Length - 1] + "','" + sLog + "','" + DateTime.Now.ToString() + "','" + this.GetIP() + "')"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //中文分页
    public static PagedDataSource PageBar(DataSet ds, string dsName, Table sTable, int pagesize, int s)
    {
        HttpRequest Request = HttpContext.Current.Request;
        string[] stra;
        string str = "";
        string url = Request.Url.AbsoluteUri.ToString();
        int count = 0;//统计&
        int count2 = 0;//统计?
        for (int i = 0; i < url.Length; i++)
        {
            if (url[i] == '&')
            {
                count++;
            }
        }
        for (int i = 0; i < url.Length; i++)
        {
            if (url[i] == '?')
            {
                count2++;
            }
        }
        switch (count)
        {
            case 0:
                str = url + "&";
                break;
            case 1:
                stra = url.Split('&');
                str = stra[0] + "&";
                break;
            case 2:
                stra = url.Split('&');
                str = stra[0] + "&" + stra[1] + "&";
                break;
            case 3:
                stra = url.Split('&');
                str = stra[0] + "&" + stra[1] + "&" + stra[2] + "&";
                break;
        }
        if (s == 0)
        {
            if (count2 == 0)
            {
                str = url + "?";
            }
            else
            {
                stra = url.Split('?');
                str = stra[0] + "?";
            }
        }
        int curpage;
        if (Request.QueryString["page"] == null)
        {
            curpage = 1;
        }
        else
        {
            curpage = Convert.ToInt32(Request.QueryString["page"].ToString());
        }
        PagedDataSource ps = new PagedDataSource();
        ps.DataSource = ds.Tables[dsName].DefaultView;
        ps.AllowPaging = true;
        ps.PageSize = pagesize;
        if (Convert.ToInt32(Request.QueryString["page"]) < 1)
        {
            curpage = 1;
        }
        if (Convert.ToInt32(Request.QueryString["page"]) > ps.PageCount)
        {
            curpage = ps.PageCount;
        }
        ps.CurrentPageIndex = curpage - 1;
        TableRow tr = new TableRow();
        TableCell tc;
        HyperLink h1;
        h1 = new HyperLink();
        h1.Text = "上一页";
        h1.NavigateUrl = str + "page=" + (curpage - 1);
        if (curpage <= 1)
        {
            h1.Enabled = false;
            h1.CssClass = "disabled_tnt_pagination";
        }
        tc = new TableCell();
        tc.Controls.Add(h1);
        tr.Controls.Add(tc);
        if (curpage <= 10)
        {
            if (ps.PageCount > 10)
            {
                for (int i = 1; i <= 10; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
            }
            else
            {
                for (int i = 1; i <= ps.PageCount; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
            }
        }
        if (curpage > 10 && curpage <= 20)
        {
            if (ps.PageCount >= 20)
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 11; i <= 20; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
            }
            else
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 11; i <= ps.PageCount; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
            }
        }
        if (curpage > 20 && curpage <= 30)
        {
            if (ps.PageCount >= 30)
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 21; i <= 30; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
            }
            else
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 21; i <= ps.PageCount; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
            }
        }
        if (curpage > 30 && curpage <= 40)
        {
            if (ps.PageCount >= 30)
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 31; i <= 40; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
            }
            else
            {
                tc = new TableCell();
                h1 = new HyperLink();
                h1.Text = "…";
                tc.Controls.Add(h1);
                tr.Controls.Add(tc);
                for (int i = 31; i <= ps.PageCount; i++)
                {
                    if (curpage != i)
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.NavigateUrl = str + "page=" + i;
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                    else
                    {
                        tc = new TableCell();
                        h1 = new HyperLink();
                        h1.Text = Convert.ToString(i);
                        h1.CssClass = "active_tnt_link";
                        tc.Controls.Add(h1);
                        tr.Controls.Add(tc);
                    }
                }
            }
        }
        h1 = new HyperLink();
        h1.Text = "下一页";
        if (curpage >= ps.PageCount)
        {
            h1.Enabled = false;
            h1.CssClass = "disabled_tnt_pagination";
        }
        if (ps.PageCount != 0)
        {
            if (curpage > 0)
            {
                h1.NavigateUrl = str + "page=" + (curpage + 1);
            }
            else
            {
                h1.NavigateUrl = str + "page=" + (curpage + 2);
            }
        }
        else
        {
            h1.Enabled = false;
            h1.CssClass = "disabled_tnt_pagination";
        }
        tc = new TableCell();
        tc.Controls.Add(h1);
        tr.Controls.Add(tc);
        sTable.Controls.Add(tr);
        return ps;
    }

}
