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

public partial class UserSynchro : System.Web.UI.Page
{

    public string Action;
    public string SysType_Source, DbType_Source, AcFile_Source, SqlServer_Source, SqlDbName_Source, SqlUser_Source, SqlPass_Source;
    public string SysType_Remote, DbType_Remote, AcFile_Remote, SqlServer_Remote, SqlDbName_Remote, SqlUser_Remote, SqlPass_Remote;
    public bool NeedOverwrite, NeedBatch;
    public int TotalRecord, SkipRecord, OverwriteRecord, SuccessRecord, FailedRecord, BatchNum;
    public string ConnStr;
    public string ServerMsg, SQL_Source;
    public IDbConnection  Conn_Source,Conn_Remote;
    public IDbDataAdapter DataAdapter_Source, DataAdapter_Remote;
    public string source_table, remote_table, PE_table, remote_c, source_c;

    /// <summary>
    /// 程序入口
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {

        Action = base.Request["action"];
        switch (Action)
        {
            case "TestConn":  //测试链接
                TestConn();
                break;
            case "start":   //开始
                Main();
                break;
        }

       
    }


    /// <summary>
    /// 测试链接
    /// </summary>
    public void TestConn()
    {
        string TestType;
        TestType = Request.Form["testtype"];
        if (TestType == "source")
        {
            GetSourceInfo();
            TestSource();
            CleanConns();
            ServerMsg = "{0}源数据库连接测试成功。";
            WriteMsg();
        }
        else
        {
            GetRemoteInfo();
            TestRemote();
            CleanConns();
            ServerMsg = "{0}目标数据库连接测试成功。";
            WriteMsg();
        }

    }

    /// <summary>
    /// 同步主函数
    /// </summary>
    public void Main()
    {
        GetSourceInfo();
        GetRemoteInfo();
        GetOptionInfo();
        InitHTML();
        CheckParam();
        TestSource();
        IDbCommand cmd = Conn_Source.CreateCommand();
        cmd.CommandText = GetSqlString();
        DataSet ds = new DataSet();
        DataAdapter_Source.SelectCommand = cmd;
        DataAdapter_Source.Fill(ds);
        if (ds.Tables[0].Rows.Count>0)
        {
            TotalRecord = ds.Tables[0].Rows.Count-1;
        }
        else
        {
            ServerMsg = "源数据库中没有记录，不需要同步！";
            WriteMsg();
        }
        SuccessRecord = Convert.ToInt32(Request.Form["SucNum"]);
        SkipRecord = Convert.ToInt32(Request.Form["SkipNum"]);
        OverwriteRecord = Convert.ToInt32(Request.Form["OverNum"]);
        FailedRecord = Convert.ToInt32(Request.Form["FailNum"]);

        int Batch, Batchs, StartID, EndID;
        if (NeedBatch)
        {
            Batch = Convert.ToInt32(Request.QueryString["Batch"]);
            if (Batch == 0)
            {
                Batch = 1;
            }
            Batchs = (TotalRecord / BatchNum) + 1;
            if ((Batch - Batchs) > 0)
            {
                Batch = 1;
            }
            StartID = (Batch - 1) * BatchNum;
            EndID = Batch * BatchNum - 1;
        }
        else
        {
        Batch = 1;
        Batchs = 1;
        StartID = 0;
        BatchNum = TotalRecord;
        EndID = TotalRecord;

        }
        if (EndID > TotalRecord)
            EndID = TotalRecord;
        RefreshHTMLStart((TotalRecord+1).ToString(), Batchs.ToString(), Batch.ToString(), (StartID + 1).ToString(), (EndID+1).ToString());
        if ((StartID - TotalRecord) <= 0)
        {
            TestRemote();

            for (int i = StartID; i <= EndID; i++)
            {
                AddNewUser(ds.Tables[0].Rows[i][0].ToString(), ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][2].ToString(), ds.Tables[0].Rows[i][3].ToString(), ds.Tables[0].Rows[i][4].ToString(), SysType_Remote, DbType_Remote);

            }
        }
        if (EndID == TotalRecord)
        {
            OutputSubmit(true, Batch);
        }
        else
        {
            OutputSubmit(false, Batch);
        }
    }




    /// <summary>
    /// 测试数据源
    /// </summary>
    public void TestSource()
    {
        if (DbType_Source == "" || ((DbType_Source == "access") && (AcFile_Source == "")) || ((DbType_Source == "sql") && (SqlServer_Source == "" || SqlDbName_Source == "" || SqlUser_Source == "")))
        {
            ServerMsg = "缺少连接目标数据库的必须参数！";
            WriteMsg();
        }
        OpenDatabase("Source");
        string sql="";
        switch (SysType_Source)
        {
            case "powereasy":
                sql = "SELECT TOP 1 * FROM "+PE_table;
                break;
            case "dvbbs":
                sql = "SELECT TOP 1 * FROM " + source_table + "User";
                break;
        }
        MyExecute("Source", sql, "所选程序类型与数据库结构不匹配！");
    }
    /// <summary>
    /// 测试目标数据
    /// </summary>
    public void TestRemote()
    {
        if (DbType_Remote == "" || ((DbType_Remote == "access") && (AcFile_Remote == "")) || ((DbType_Remote == "sql") && (SqlServer_Remote == "" || SqlDbName_Remote == "" || SqlUser_Remote == "")))
        {
            ServerMsg = "缺少连接目标数据库的必须参数！";
            WriteMsg();
        }
        OpenDatabase("Remote");
        string sql="";
        switch (SysType_Remote)
        {
            case  "powereasy":
                sql = "SELECT TOP 1 * FROM "+PE_table;
                break;
            case "dvbbs":
                sql = "SELECT TOP 1 * FROM " + remote_table + "User";
                break;
        }
        MyExecute("Remote", sql, "所选程序类型与数据库结构不匹配！");
    }



    /// <summary>
    /// 增加用户处理
    /// </summary>
    /// <param name="UserName">用户名</param>
    /// <param name="UserPassword"></param>
    /// <param name="UserEmail"></param>
    /// <param name="UserQuestion"></param>
    /// <param name="UserAnswer"></param>
    /// <param name="SysType"></param>
    /// <param name="DbsType"></param>
    public void AddNewUser(string UserName, string UserPassword, string UserEmail, string UserQuestion, string UserAnswer, string SysType, string DbsType)
    {   
        IDbCommand cmd=Conn_Remote.CreateCommand();
        cmd.CommandText="SELECT * FROM " + GetUserTable(SysType) + " WHERE UserName='" + UserName + "'";
        IDataReader read=cmd.ExecuteReader();
        if (!read.Read())
        {
            read.Close();
            if (AddUser(UserName, UserPassword, UserEmail, UserQuestion, UserAnswer, SysType, DbsType))
            {
                SuccessRecord++;
            }
            else
            {
                FailedRecord++;
            }

        }
        else
        {
            read.Close();
            if (NeedOverwrite)
            {
                if (UpdateUser(UserName, UserPassword, UserEmail, UserQuestion, UserAnswer, SysType, DbsType))
                {
                    OverwriteRecord++;
                }
                else
                {
                    FailedRecord++;
                }
            }
            else
            {
                SkipRecord++;
            }

        }
        
        RefreshHTMLEnd(SuccessRecord.ToString(), SkipRecord.ToString(), OverwriteRecord.ToString(), FailedRecord.ToString());

    }


    /// <summary>
    /// 增加用户
    /// </summary>
    /// <param name="UserName"></param>
    /// <param name="UserPassword"></param>
    /// <param name="UserEmail"></param>
    /// <param name="UserQuestion"></param>
    /// <param name="UserAnswer"></param>
    /// <param name="SysType"></param>
    /// <param name="DbsType"></param>
    /// <returns></returns>
    public bool AddUser(string UserName, string UserPassword, string UserEmail, string UserQuestion, string UserAnswer, string SysType, string DbsType)
    {
        if (remote_c == "old" && UserPassword.Length == 32)
        {
            UserPassword = UserPassword.Substring(8, 16);
        }
        if (remote_c == "old" && UserAnswer.Length == 32)
        {
            UserAnswer = UserAnswer.Substring(8, 16);
        }
        IDbCommand cmd;
        try
        {
            switch (SysType)
            {
                case "powereasy":
                    IDataReader read;
                    cmd = Conn_Remote.CreateCommand();
                    long UserID;
                    cmd.CommandText = "SELECT MAX(UserID) FROM "+PE_table;
                    read = cmd.ExecuteReader();
                    if (read.Read())
                    {
                        UserID = long.Parse(read[0].ToString()) + 1;
                    }
                    else
                    {
                        UserID = 1;
                    }
                    read.Close();
 
                    cmd.CommandText = @"INSERT INTO ["+PE_table+@"] ([UserID], [GroupID],[UserName],[UserPassword],[Question],[Answer],[Email],[RegTime],[JoinTime],[LoginTimes], [LastLoginTime])
	                            VALUES(@UserID,1,@UserName,@UserPassword,@Question,@Answer,@Email,'" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "',0,'" + DateTime.Now.ToString() + "')";
                    IDataParameter par1 = cmd.CreateParameter();
                    par1.ParameterName = "@UserID";
                    par1.DbType = DbType.Int32;
                    par1.Value = UserID;
                    cmd.Parameters.Add(par1);
                    IDataParameter par2 = cmd.CreateParameter();
                    par2.ParameterName = "@UserName";
                    par2.DbType = DbType.String;
                    par2.Value = UserName;
                    cmd.Parameters.Add(par2);
                    IDataParameter par3 = cmd.CreateParameter();
                    par3.ParameterName = "@UserPassword";
                    par3.DbType = DbType.String;
                    par3.Value = UserPassword;
                    cmd.Parameters.Add(par3);
                    IDataParameter par4 = cmd.CreateParameter();
                    par4.ParameterName = "@Question";
                    par4.DbType = DbType.String;
                    par4.Value = UserQuestion;
                    cmd.Parameters.Add(par4);
                    IDataParameter par5 = cmd.CreateParameter();
                    par5.ParameterName = "@Answer";
                    par5.DbType = DbType.String;
                    par5.Value = UserAnswer;
                    cmd.Parameters.Add(par5);
                    IDataParameter par6 = cmd.CreateParameter();
                    par6.ParameterName = "@Email";
                    par6.DbType = DbType.String;
                    par6.Value = UserEmail;
                    cmd.Parameters.Add(par6);
                    cmd.ExecuteNonQuery();
                    break;
                case "dvbbs":
                    cmd = Conn_Remote.CreateCommand();
                    cmd.CommandText = @"insert into " + remote_table + @"User ([UserQuesion], [UserAnswer],[UserEmail],[UserPassword], [UserName])
                  values (@question,@answer,@email,@password,@name)";
                    IDataParameter parr1 = cmd.CreateParameter();
                    parr1.ParameterName = "@question";
                    parr1.DbType = DbType.String;
                    parr1.Value = UserQuestion;
                    cmd.Parameters.Add(parr1);
                    IDataParameter parr2 = cmd.CreateParameter();
                    parr2.ParameterName = "@answer";
                    parr2.DbType = DbType.String;
                    parr2.Value = UserAnswer;
                    cmd.Parameters.Add(parr2);
                    IDataParameter parr3 = cmd.CreateParameter();
                    parr3.ParameterName = "@email";
                    parr3.DbType = DbType.String;
                    parr3.Value = UserEmail;
                    cmd.Parameters.Add(parr3);
                    IDataParameter parr4 = cmd.CreateParameter();
                    parr4.ParameterName = "@password";
                    parr4.DbType = DbType.String;
                    parr4.Value = UserPassword;
                    cmd.Parameters.Add(parr4);
                    IDataParameter parr5 = cmd.CreateParameter();
                    parr5.ParameterName = "@name";
                    parr5.DbType = DbType.String;
                    parr5.Value = UserName;
                    cmd.Parameters.Add(parr5);
                    cmd.ExecuteNonQuery();
                    break;
            }
        }
        catch(Exception ex)
        {
            ServerMsg = "{0}源数据库连接测试成功。" + ex.Message.ToString();
            WriteMsg();
            return false;
        }
        return true;
    }


    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="UserName"></param>
    /// <param name="UserPassword"></param>
    /// <param name="UserEmail"></param>
    /// <param name="UserQuestion"></param>
    /// <param name="UserAnswer"></param>
    /// <param name="SysType"></param>
    /// <param name="DbType"></param>
    /// <returns></returns>
    public bool UpdateUser(string UserName,string UserPassword,string UserEmail,string UserQuestion,string UserAnswer,string SysType,string DbsType)
    {
        if (string.IsNullOrEmpty(UserPassword) || string.IsNullOrEmpty(UserName))
        {
            return false;
        }
        if (string.IsNullOrEmpty(UserEmail))
        {
            UserEmail = "";
        }
        if (string.IsNullOrEmpty(UserQuestion))
        {
            UserQuestion = "";
        }
        if (string.IsNullOrEmpty(UserAnswer))
        {
            UserAnswer = "";
        }
        if (remote_c == "old" && UserPassword.Length == 32)
        {
            UserPassword = UserPassword.Substring(8, 16);
        }
        if (remote_c == "old" && UserAnswer.Length == 32)
        {
            UserAnswer = UserAnswer.Substring(8, 16);
        }
        UserName = UserName.Replace("'", "");
        UserEmail = UserEmail.Replace("'", "");
        UserQuestion = UserQuestion.Replace("'", "");
        string tempSqlStr="";
        switch (SysType)
        {
            case "powereasy" :
                tempSqlStr = "UPDATE "+PE_table+" SET UserPassword='" + UserPassword + "',Email='" + UserEmail + "',Question='" + UserQuestion + "',Answer='" + UserAnswer + "' WHERE UserName='" + UserName + "'";
                break;
            case "dvbbs" :
                tempSqlStr = "UPDATE " + remote_table + "User SET UserPassword='" + UserPassword + "',UserEmail='" + UserEmail + "',UserQuesion='" + UserQuestion + "',UserAnswer='" + UserAnswer + "' WHERE UserName='" + UserName + "'";
                break;
        }
        try
        {
            IDbCommand cmd = Conn_Remote.CreateCommand();
            cmd.CommandText = tempSqlStr;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            ServerMsg = "{0}源数据库连接测试成功。"+ex.Message.ToString();
            WriteMsg();
            return false;
        }
        return true;
    }



    /// <summary>
    /// asp版,用途未知
    /// </summary>
    /// <param name="DbsType"></param>
    /// <returns></returns>
    public string GetTrueString(string DbsType)
    {
        if (DbsType == "access")
        {
           return "true";
        }
        else
        {
            return "1";
        }
    }

    /// <summary>
    /// asp版,用途未知
    /// </summary>
    /// <param name="DbsType"></param>
    /// <returns></returns>
    public string GetFalseString(string DbsType)
    {
        if (DbsType == "access")
        {
            return  "False";
        }
        else
        {
            return  "0";
        }
    }

    /// <summary>
    /// asp版,用途未知
    /// </summary>
    /// <param name="DbsType"></param>
    /// <returns></returns>
    public string GetNowString(string DbsType)
    {
        if(DbsType == "access")
        {
            return "Now()";
        }else{
           return "GetDate()";
        }
    }



    /// <summary>
    /// 得到源数据库信息
    /// </summary>
    public void GetSourceInfo()
    {
    SysType_Source = Request.Form["source_systype"].Trim();
    DbType_Source = Request.Form["source_dbtype"].Trim();
    AcFile_Source = Request.Form["source_dbpath"].Trim();
    SqlServer_Source = Request.Form["source_servername"].Trim();
    SqlDbName_Source =Request.Form["source_dbname"].Trim();
    SqlUser_Source = Request.Form["source_username"].Trim();
    SqlPass_Source = Request.Form["source_password"].Trim();
    if (DbType_Source == "access")
    {
        source_table = Request.Form["ac_source_table"].Trim();
        source_c = Request.Form["ac_source_c"];
    }
    else
    {
        source_table = Request.Form["sql_source_table"].Trim();
        source_c = Request.Form["sql_source_c"];
    }
    }


    /// <summary>
    /// 输出错误
    /// </summary>
    public void WriteMsg()
    {

    if (Action == "TestConn")
    {
        Response.ContentType = "text/html";
        Response.Charset = "gb2312";
        Response.AddHeader("contenttype", "text/xml; charset=gb2312");
        Response.ContentEncoding = Encoding.GetEncoding("gb2312");
        Response.Write(ServerMsg);
        Response.End();
    }
    else
    {
        Response.ContentEncoding = Encoding.GetEncoding("gb2312");
        Response.Write ("<script type=\"text/javascript\" language=\"javascript\">");
        Response.Write ("document.getElementById(\"wait\").innerHTML = \"" + ServerMsg + "\";"); 
        Response.Write ("</script>");
        Response.End();
    }
    }
    /// <summary>
    /// 得到目标数据库信息
    /// </summary>
    public void GetRemoteInfo()
    {
    SysType_Remote =Request.Form["remote_systype"].Trim();
    DbType_Remote = Request.Form["remote_dbtype"].Trim();
    AcFile_Remote = Request.Form["remote_dbpath"].Trim();
    SqlServer_Remote = Request.Form["remote_servername"].Trim();
    SqlDbName_Remote = Request.Form["remote_dbname"].Trim();
    SqlUser_Remote = Request.Form["remote_username"].Trim();
    SqlPass_Remote = Request.Form["remote_password"].Trim();
    if (DbType_Remote == "access")
    {
        remote_table = Request.Form["ac_remote_table"].Trim();
        remote_c = Request.Form["ac_remote_c"];
    }
    else
    {
        remote_table = Request.Form["sql_remote_table"].Trim();
        remote_c = Request.Form["sql_remote_c"];
    }
    }

    /// <summary>
    /// 得到配置信息
    /// </summary>
    public void GetOptionInfo()
    {
        string m_NeedOverwrite, m_NeedBatch;
        m_NeedOverwrite =Request.Form["overwrite"];
        m_NeedBatch=Request.Form["batch"];
        BatchNum=Convert.ToInt32(Request.Form["batchnum"]);
        if (m_NeedOverwrite == "True")
        {
            NeedOverwrite =true;
        }
        else
        {
            NeedOverwrite =false;
        }
        if (m_NeedBatch == "True")
        {
            NeedBatch = true;
        }
        else
        {
            NeedBatch = false;
        }
    }

    /// <summary>
    /// 输出html,为下一批准备
    /// </summary>
    public void InitHTML()
    {
        Response.Clear();
        Response.ContentEncoding = Encoding.GetEncoding("gb2312");
        Response.Write(@"
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html>
<head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=gb2312"" />
<title>PDO_API统一接口数据同步程序</title>
<link href=""Code/style.css"" rel=""stylesheet"" type=""text/css"" />
</head>
<body>
<div class=""border"" id=""outbox"">
    <div class=""topbg center bold head"">PDO_API统一接口数据同步程序</div>
    <div id=""intro""> <span id=""subtitle"" class=""bold"">操作说明</span>：
        <p id=""introcontent"">正在进行用户数据同步操作，此过程视数据量大小、服务器性能和网络状况需要较长时间来完成，此过程中切勿刷新或者关闭当前浏览器窗口。</p>
        <hr style=""width:100%;height:1px;color:#666"" />
        <div id=""body4"">
            <div class=""tdbg"" id=""bodymain"">
                <div class=""line"">
					<strong>用户总数：</strong>&nbsp;共 <span id=""totalnum"">...</span> 条 分为 <span id=""batchs"">...</span> 批处理<br/>
				</div>
				<div class=""line"">
					<strong>当前处理：</strong>&nbsp;第 <span id=""currentbatch"">...</span> 批 <span id=""processnum"">...</span> 条
				</div>
				<div class=""line"">
					<strong>处理进度：</strong>&nbsp;新增 <span id=""successnum"">...</span> 条/覆盖 <span id=""overwritenum"">...</span> 条/跳过 <span id=""skipnum"">...</span> 条/失败 <span id=""failnum"">...</span> 条
				</div>
            </div>
        </div>
        <div id=""wait"" style=""width:100%;color:red;font-weight:bold;line-height:18px;text-align:center;"">正在处理您的请求，请稍候...</div>
        <hr style=""width:100%;height:1px;color:#666"" />
        <div class=""center""><input type=""button"" id=""btn_back"" value=""上一步"" onclick=""GoPreview()"" disabled=""disabled"" />&nbsp;&nbsp;<input type=""button"" id=""btn_go"" value=""完 成"" onclick=""window.close()"" disabled=""disabled"" /></div>
		<div id=""formdiv"" style=""display:none"">
            <form name=""myform"" id=""myform"" action=""UserSynchro.aspx?action=start&batch=2"" method=""post"">
                <input type=""hidden"" name=""source_systype"" id=""source_systype"" value="""+SysType_Source+ @""" />
                <input name=""source_dbtype"" type=""hidden"" id=""source_dbtype"" value="""+DbType_Source+@""" />
                <input name=""source_dbpath"" type=""hidden"" id=""source_dbpath"" value="""+AcFile_Source+@""" />
                <input name=""source_servername"" type=""hidden"" id=""source_servername"" value="""+SqlServer_Source+@""" />
                <input name=""source_dbname"" type=""hidden"" id=""source_dbname"" value="""+SqlDbName_Source+@""" />
                <input name=""source_username"" type=""hidden"" id=""source_username"" value="""+SqlUser_Source+@""" />
                <input name=""source_password"" type=""hidden"" id=""source_password"" value="""+SqlPass_Source+@""" />
                 <input name=""sql_source_table"" type=""hidden"" id=""sql_source_table"" value="""+source_table+@""" />
                  <input name=""ac_source_table"" type=""hidden"" id=""ac_source_table"" value="""+source_table+@""" />
                 <input name=""sql_source_c"" type=""hidden"" id=""sql_source_c"" value=""" + source_c + @""" />
                  <input name=""ac_source_c"" type=""hidden"" id=""ac_source_c"" value=""" + source_c + @""" />               
                <input name=""remote_systype"" type=""hidden"" id=""remote_systype"" value=""" +SysType_Remote+@""" />
                <input name=""remote_dbtype"" type=""hidden"" id=""remote_dbtype"" value="""+DbType_Remote+@""" />
                <input name=""remote_dbpath"" type=""hidden"" id=""remote_dbpath"" value="""+AcFile_Remote+@""" />
                <input name=""remote_servername"" type=""hidden"" id=""remote_servername"" value="""+SqlServer_Remote+@""" />
                <input name=""remote_dbname"" type=""hidden"" id=""remote_dbname"" value="""+SqlDbName_Remote+@""" />
                <input name=""remote_username"" type=""hidden"" id=""remote_username"" value="""+SqlUser_Remote+@""" />
                <input name=""remote_password"" type=""hidden"" id=""remote_password"" value="""+SqlPass_Remote+@""" />
               <input name=""sql_remote_table"" type=""hidden"" id=""sql_source_table"" value="""+remote_table+@""" />
                  <input name=""ac_remote_table"" type=""hidden"" id=""ac_source_table"" value="""+remote_table+@""" /> 
                  <input name=""sql_remote_c"" type=""hidden"" id=""sql_source_c"" value=""" + remote_c + @""" />
                  <input name=""ac_remote_c"" type=""hidden"" id=""ac_source_c"" value=""" + remote_c + @""" />                  
		<input name=""overwrite"" type=""hidden"" id=""overwrite"" value=""" +NeedOverwrite+@""" />
                <input name=""batch"" type=""hidden"" id=""batch"" value="""+ NeedBatch+@""" />
                <input name=""batchnum"" type=""hidden"" id=""batchnum"" value=""" + BatchNum + @""" />
                <input name=""SucNum"" type=""hidden"" id=""SucNum"" value=""0"" />
                <input name=""SkipNum"" type=""hidden"" id=""SkipNum"" value=""0"" />
                <input name=""OverNum"" type=""hidden"" id=""OverNum"" value=""0"" />
                <input name=""FailNum"" type=""hidden"" id=""FailNum"" value=""0"" />
            </form>
        </div>
    </div>
</div>
<br/>
<div class=""border center"" id=""copyright"">Copyright &copy; 2004 - 2006 PowerEasy Inc. All Rights Reserved<br/>
    Powered By UserSynchro 2.0 Build 0514</div>
</body>
</html>
         ");
        Response.Flush();
    }

    /// <summary>
    /// 检查数据库参数
    /// </summary>
    public void CheckParam()
    {
        if (DbType_Source == "" || DbType_Remote == "")
        {
            ServerMsg = "缺少关键参数，程序无法继续运行";
            WriteMsg();
        }
        if(DbType_Source == "access" && AcFile_Source == "")
        {
            ServerMsg = "源数据库选择为Access数据库，则数据库文件路径不能为空";
            WriteMsg();
        }
        if (DbType_Source == "sql" && (SqlServer_Source == "" || SqlDbName_Source == "" || SqlUser_Source == ""))
        {
            ServerMsg = "源数据库选择为SQL数据库，SQL服务器的相关信息不能为空";
            WriteMsg();
        }
        if(DbType_Remote == "access" && AcFile_Remote == "")
        {
            ServerMsg = "目标数据库选择为Access数据库，则数据库文件路径不能为空";
            WriteMsg();
        }
        if(DbType_Remote == "sql" && (SqlServer_Remote == "" || SqlDbName_Remote == "" || SqlUser_Remote == ""))
        {
            ServerMsg = "目标数据库选择为SQL数据库，SQL服务器的相关信息不能为空";
            WriteMsg();
        }
    }

    /// <summary>
    /// 得到用户表
    /// </summary>
    /// <param name="strSysType"></param>
    /// <returns></returns>
    public string GetUserTable(string strSysType)
    {
      switch(strSysType)
      {
          case "powereasy" :
                     return PE_table;
          case "dvbbs" :
                     return remote_table + "User";
       }
        return "";
    }

    /// <summary>
    ///取得用户表查询字符串
    /// </summary>
    /// <returns></returns>
    public string GetSqlString()
    {
        switch (SysType_Source)
        {
            case "powereasy" :
                return "SELECT UserName,UserPassword,Email,Question,Answer FROM " + PE_table + " ORDER BY UserID";
            case "dvbbs":
                return "SELECT UserName,UserPassword,UserEmail,UserQuesion,UserAnswer FROM [" + source_table + "User] ORDER BY UserID";
        }
        return "";
    }

    /// <summary>
    /// 刷新信息
    /// </summary>
    /// <param name="iTotal"></param>
    /// <param name="iBatchs"></param>
    /// <param name="iBatch"></param>
    /// <param name="iStart"></param>
    /// <param name="iEnd"></param>
    public void  RefreshHTMLStart(string iTotal,string iBatchs,string iBatch,string iStart,string iEnd)
    {
    Response.Write (@"<script type=""text/javascript"" language=""javascript"">");
    Response.Write (@"document.getElementById(""totalnum"").innerHTML = """ + iTotal + @""";" );
    Response.Write (@"document.getElementById(""batchs"").innerHTML = """ + iBatchs + @""";" );
    Response.Write (@"document.getElementById(""currentbatch"").innerHTML = """ + iBatch + @""";" );
    Response.Write (@"document.getElementById(""processnum"").innerHTML = """ + iStart + " - " + iEnd + @""";" );
    Response.Write ("</script>");
    }


    /// <summary>
    /// 最后输出
    /// </summary>
    /// <param name="iSuccess"></param>
    /// <param name="iSkip"></param>
    /// <param name="iOverwrite"></param>
    /// <param name="iFailed"></param>
    public void RefreshHTMLEnd(string iSuccess,string iSkip,string iOverwrite,string iFailed)
    {
    Response.Write (@"<script type=""text/javascript"" language=""javascript"">");
    Response.Write (@"document.getElementById(""successnum"").innerHTML = """ + iSuccess + @""";" );
    Response.Write (@"document.getElementById(""overwritenum"").innerHTML = """ + iOverwrite + @""";");
    Response.Write(@"document.getElementById(""skipnum"").innerHTML = """ + iSkip + @""";" );
    Response.Write (@"document.getElementById(""failnum"").innerHTML = """ + iFailed + @""";" );
    Response.Write ("</script>");
    }



    /// <summary>
    /// 更新输出
    /// </summary>
    /// <param name="blnFinished"></param>
    /// <param name="Batch"></param>
    public void OutputSubmit(bool blnFinished, int Batch)
    {
        CleanConns();
        Response.Write (@"<script type=""text/javascript"" language=""javascript"">");
      if(blnFinished)
      {
        Response.Write( @"document.getElementById(""wait"").innerHTML = ""操作已完成，感谢您对动易的信任与支持！"";");
        Response.Write(@"document.getElementById(""btn_go"").removeAttribute(""disabled"");" );
      }else{
        Response.Write(@"document.forms[0].SucNum.value = """ + SuccessRecord + @""";");
        Response.Write (@"document.forms[0].SkipNum.value = """ + SkipRecord + @""";");
        Response.Write (@"document.forms[0].OverNum.value = """ + OverwriteRecord + @""";");
        Response.Write (@"document.forms[0].FailNum.value = """ + FailedRecord + @""";");
        Response.Write(@"document.forms[0].action = ""UserSynchro.aspx?action=start&batch=" + (Batch + 1) + @""";");
        // Response.Write(@"document.forms[0].submit();");
        Response.Write(@"timei2=0; 
                                                function   Stoptime(s){//s为停止的时间 
                                                 if   (   timei2++ <s){ 
                                                 setTimeout( ""Stoptime( ""+s+""); "",1000);   
                                                  } 
                                               else{ 
                                               document.forms[0].submit();
                                               }  
                                               }
                                               Stoptime(2);");
            }
    Response.Write( "</script>");

   }


    /// <summary>
    /// 关闭链接
    /// </summary>
    public void CleanConns()
    {
        if (Conn_Remote != null)
            Conn_Remote.Close();
        if (Conn_Source != null)
            Conn_Source.Close();
    }


    /// <summary>
    /// 数据库操作
    /// </summary>
    /// <param name="OpenType"></param>
    public void OpenDatabase(string OpenType)
    {
        string strNameOfDb="";
        try
        {
            if (OpenType == "Source")
            {
                strNameOfDb = "源数据库";
                if (DbType_Source == "access")
                {
                    PE_table = "PE_User";
                    ConnStr = "Provider = Microsoft.JET.OleDb.4.0; Data Source = " + Server.MapPath(AcFile_Source) + ";";
                    Conn_Source = new OleDbConnection();
                    Conn_Source.ConnectionString = ConnStr;
                    Conn_Source.Open();
                    DataAdapter_Source = new OleDbDataAdapter();
                }
                else
                {
                    PE_table = "PE_Users";
                    ConnStr = "User ID = " + SqlUser_Source + "; Password = " + SqlPass_Source + "; Initial Catalog = " + SqlDbName_Source + "; Data Source = " + SqlServer_Source + ";";
                    Conn_Source = new SqlConnection();
                    Conn_Source.ConnectionString = ConnStr;
                    Conn_Source.Open();
                    DataAdapter_Source = new SqlDataAdapter();
                }

            }
            else
            {
                strNameOfDb = "目标数据库";
                if (DbType_Remote == "access")
                {
                    PE_table = "PE_User";
                    ConnStr = "Provider = Microsoft.JET.OleDb.4.0; Data Source = " + Server.MapPath(AcFile_Remote) + ";";
                    Conn_Remote = new OleDbConnection();
                    Conn_Remote.ConnectionString = ConnStr;
                    Conn_Remote.Open();
                    DataAdapter_Remote = new OleDbDataAdapter();
                }
                else
                {
                    PE_table = "PE_Users";
                    ConnStr = "User ID = " + SqlUser_Remote + "; Password = " + SqlPass_Remote + "; Initial Catalog = " + SqlDbName_Remote + "; Data Source = " + SqlServer_Remote + ";";
                    Conn_Remote = new SqlConnection();
                    Conn_Remote.ConnectionString = ConnStr;
                    Conn_Remote.Open();
                    DataAdapter_Remote = new SqlDataAdapter();
                }

            }
        }
        catch(Exception ex)
        {
            //FoundErr = true;
            ServerMsg = "创建" + strNameOfDb + "的连接失败，请检查所提交的信息。以下信息供参考： 连接代码：[" + ConnStr+ex.Message.ToString() + "]";
            WriteMsg();
        }

    }

    /// <summary>
    /// 测试数据库用
    /// </summary>
    /// <param name="ExecuteType"></param>
    /// <param name="strToExecute"></param>
    /// <param name="strErr"></param>
    public void MyExecute(string ExecuteType, string strToExecute, string strErr)
    {

        try
        {
            if (ExecuteType == "Source")
            {
                IDbCommand cmd = Conn_Source.CreateCommand();
                cmd.CommandText = strToExecute;
                cmd.ExecuteNonQuery();
            }
            else
            {
                IDbCommand cmd = Conn_Remote.CreateCommand();
                cmd.CommandText = strToExecute;
                cmd.ExecuteNonQuery();
            }
        }
        catch 
        {
            CleanConns();
            ServerMsg = strErr + "以下信息供参考： SQL语句：[" + strToExecute + "]";
            WriteMsg();

        }

    }

}
