using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using Lskj.Control;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace AFKAbutment
{
public partial class Form1 : Form
{
public Form1(string[] args)
{
arg = args;
this.FormClosed += Form1_FormClosed;
this.KeyDown += Form1_KeyDown;
InitializeComponent();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (thread != null)
{
thread.Abort();
}
this.Dispose();
this.Close();
}
public string[] arg;
public bool rightClickExecute = false;
public System.Threading.Thread thread = null;
public bool isStop = false;
public System.Timers.Timer timer1 = new System.Timers.Timer();
public System.Timers.Timer timer2 = new System.Timers.Timer();
public System.Timers.Timer timer3 = new System.Timers.Timer();
public string separator = "Lserp$specialTag";//分割符
//初始化
private void Form1_Load(object sender, EventArgs e)
{
this.startBtn.Appearance.BackColor = Color.FromArgb(140, 208, 1);
this.startBtn.MouseHover += new EventHandler(OnStartBtn_MouseHover);
this.startBtn.MouseLeave += new EventHandler(OnStartBtn_MouseLeave);
this.stopBtn.MouseHover += new EventHandler(OnStoptBtn_MouseHover);
this.stopBtn.MouseLeave += new EventHandler(OnStopBtn_MouseLeave);
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer1_Elapsed);
this.timer2.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer2_Elapsed);
this.timer3.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer3_Elapsed);
//afk
afkSeverId.Text = IniHelper.Read("Setting.ini", "AFK", "serverName"); //地址
afkPortNumber.Text = IniHelper.Read("Setting.ini", "AFK", "port"); //端口
afkDataBase.Text = IniHelper.Read("Setting.ini", "AFK", "dbName");//数据库名
afkName.Text = IniHelper.Read("Setting.ini", "AFK", "user");//用户名
afkPassword.Text = IniHelper.Read("Setting.ini", "AFK", "password"); //密码
//ls
lsSeverId.Text = IniHelper.Read("Setting.ini", "LS", "serverName"); //地址
lsDataBase.Text = IniHelper.Read("Setting.ini", "LS", "dbName");//数据库名
lsName.Text = IniHelper.Read("Setting.ini", "LS", "user");//用户名
lsPassword.Text = IniHelper.Read("Setting.ini", "LS", "password"); //密码
//parameter
string time = IniHelper.Read("Setting.ini", "parameter", "time"); //间隔时间
if (string.IsNullOrEmpty(time)) time = "30";
if (Convert.ToInt32(time) < 30) time = "30";
intervalTime.Text = time;
intervalTime.LostFocus += new EventHandler(intervalTime_LostFocus);
if (arg.Length > 0)
{
if (arg[0].Equals("1"))
{
timer2.Interval = 10000;
timer2.Enabled = true;
}
}
InitializeDataSettings();
}
//
/// 时间间隔TextBox失去焦点事件
///
///
///
private void intervalTime_LostFocus(object sender, EventArgs e)
{
string checkStr = intervalTime.Text.ToString();
if (string.IsNullOrEmpty(checkStr)) intervalTime.Text = "30";
int check = Convert.ToInt32(intervalTime.Text.ToString());
if (check < 30)
{
intervalTime.Text = "30";
}
IniHelper.Write("parameter", "time", intervalTime.Text.ToString());
}
//判断右键列,是否要立刻同步数据
private void OnTimer3_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer3.Enabled = false;
bool isRecover = false;
if (!isStop)
{
isRecover = true;
}
DataTable synchronousTable = SqlHelper.ExecuteDataTable("select * from p_synchrTab where rightKeyTag='1' ORDER BY id");
if (synchronousTable.Rows.Count > 0)
{
if (rightClickExecute)
{
isStop = true;
timer1.Enabled = false;
RefreshLogUIThread("清空");
RefreshLogUIThread(DateTime.Now + "正在同步右键数据.\r\n");
//AFK》LS
DataRow[] performDr = synchronousTable.Select("directionTag" + "='0'");
this.getAfktoLs(performDr);
//LS》AFK
performDr = synchronousTable.Select("directionTag" + "='1'");
this.getLStoAFK(performDr);
string sql = "update p_synchrTab set rightKeyTag='0'";
SqlHelper.ExecuteNonQuery(sql);
//固定执行
DataTable dt = SqlHelper.ExecuteDataTable("select * from p_synchrTab where id='9999999'");
if (dt != null && dt.Rows.Count > 0)
{
string afterSql = dt.Rows[0]["afterSql"] + "";//同步完成后执行的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
RefreshLogUIThread(DateTime.Now + "同步右键数据结束.\r\n");
timer1.Enabled = true;
if (isRecover)
{
RefreshLogUIThread(DateTime.Now + "恢复同步.\r\n");
isStop = false;
}
else
{
RefreshLogUIThread(DateTime.Now + "请点击开始按钮恢复同步.\r\n");
}
}
else
{
isStop = true;
RefreshLogUIThread("清空");
RefreshLogUIThread(DateTime.Now + "已暂停当前同步,正在同步右键数据.\r\n");
//AFK》LS
DataRow[] performDr = synchronousTable.Select("directionTag" + "='0'");
this.getAfktoLs(performDr, true);
//LS》AFK
performDr = synchronousTable.Select("directionTag" + "='1'");
this.getLStoAFK(performDr, true);
string sql = "update p_synchrTab set rightKeyTag='0'";
SqlHelper.ExecuteNonQuery(sql);
//固定执行
DataTable dt = SqlHelper.ExecuteDataTable("select * from p_synchrTab where id='9999999'");
if (dt != null && dt.Rows.Count > 0)
{
string afterSql = dt.Rows[0]["afterSql"] + "";//同步完成后执行的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
RefreshLogUIThread(DateTime.Now + "同步右键数据结束.\r\n");
if (isRecover)
{
RefreshLogUIThread(DateTime.Now + "恢复同步.\r\n");
isStop = false;
}
else
{
RefreshLogUIThread(DateTime.Now + "请点击开始按钮恢复同步.\r\n");
}
}
}
timer3.Enabled = true;
}
//被服务打开后主动执行点击同步暗流
private void OnTimer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer2.Enabled = false;
startBtn_Click(sender, e);
}
//循环同步操作
private void OnTimer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
rightClickExecute = false;
timer1.Enabled = false;
RefreshLogUIThread("清空");
//AFK》LS
DataTable synchronousTable = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' and directionTag='0' ORDER BY id");
this.SynchroDataSingle(synchronousTable, DataDirection.AfkToLs);
//固定执行
try
{
DataTable dt = SqlHelper.ExecuteDataTable("select * from p_synchrTab where id='9999999'");
if (dt != null && dt.Rows.Count > 0)
{
string afterSql = dt.Rows[0]["afterSql"] + "";//同步完成后执行的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
}
catch (Exception)
{
}
//LS》AFK
synchronousTable = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' and directionTag='1' ORDER BY id");
this.SynchroDataSingle(synchronousTable, DataDirection.LsToAfk);
// 获取中间日志表中报错信息
getErrorLine();
timer1.Enabled = true;
rightClickExecute = true;
}
private void StartMethod()
{
try
{
RefreshLogUIThread(DateTime.Now + "正在初始化平台.\r\n");
//连接服务器
if (ConnectServer() && ConnectMySql())
{
timer3.Interval = 2000;
timer3.Enabled = true;
RefreshLogUIThread(DateTime.Now + "初始化平台成功.\r\n");
DataTable synchronousTable = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' ORDER BY id");
DataRow[] performDr = null;
//AFK》LS
performDr = synchronousTable.Select("directionTag" + "='0'");
//performDr = synchronousTable.Select("id" + "='14'");
//this.getAfktoLs(performDr);
DataTable dt = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' and directionTag='0' ORDER BY id");// and id in(38,46,47)
this.SynchroDataSingle(dt, DataDirection.AfkToLs);
performDr = synchronousTable.Select("id" + "='9999999'");
if (performDr != null && performDr.Length > 0)
{
string afterSql = performDr[0]["afterSql"] + "";//同步完成后执行的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
DataTable dts = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' and directionTag='1' ORDER BY id");//and id=36
this.SynchroDataSingle(dts, DataDirection.LsToAfk);
//LS》AFK
//performDr = synchronousTable.Select("directionTag" + "='1'");
//performDr = synchronousTable.Select("id" + "='6'");
//this.getLStoAFK(performDr);
//DataTable dt = SqlHelper.ExecuteDataTable("select * from p_synchrTab where disableTag='true' and directionTag='1' ORDER BY id");
//this.SynchroDataSingle(dt, DataDirection.LsToAfk);
// 获取中间日志表中报错信息
getErrorLine();
rightClickExecute = true;
timer1.Interval = Convert.ToInt32(intervalTime.Text.ToString()) * 1000;
timer1.Enabled = true;
}
else
{
RefreshLogUIThread(DateTime.Now + " 初始化平台失败.\r\n");
thread = null;
}
}
catch (Exception ex)
{
RefreshLogUIThread(DateTime.Now + string.Format("初始化失败.原因:{0}.\r\n", ex.Message));
}
}
private void startBtn_Click(object sender, EventArgs e)
{
if (thread == null)
{
thread = new System.Threading.Thread(StartMethod);
thread.Start();
}
else
{
RefreshLogUIThread(string.Format("恢复同步,同步中……\r\n"));
isStop = false;
}
}
private void stopBtn_Click(object sender, EventArgs e)
{
isStop = true;
}
//从AFK拿数据同步到LS中
public void getAfktoLs(DataRow[] performDr, bool isRightStop = false)
{
//afk》朗速
RefreshLogUIThread(string.Format("开始从AFK获取数据:\r\n"));
RefreshLogUIThread(string.Format("开始同步:\r\n"));
string mainTableName = string.Empty;
foreach (DataRow item in performDr)
{
try
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string targetTabSql = item["targetTabSql"] + "";//去获得的数据源sql
string synchroSql = (item["synchroSql"] + "").ToLower();//同步sql
string synLogSql = (item["synLogSql"] + "").ToLower();//同步到备份日志表中的sql
string afterSql = item["afterSql"] + "";//同步完成后执行的sql
string targetTab = string.Empty;//中间表对应的表名
string disableFieid = item["disableField"] + "";//tagid是3或者4,指定字段改变
targetTab = targetTabSql.Split('^')[0].Replace(" ", "");
mainTableName = synchroSql.Split('^')[0].Replace(" ", "");
string sql = string.Format(@"if not exists(select * from syscolumns
where id=object_id('{0}') and name='directTag')
begin
alter table {0} add directTag int
end", mainTableName);
SqlHelper.ExecuteNonQuery(sql);
//判断有无标识列
sql = string.Format(@"select CASE when (select count(1)
FROM information_schema.COLUMNS
WHERE table_schema = '{0}'
and table_name = '{1}'
AND column_name = 'isSynchro') > 0
then '1'
else '2'
end
", afkDataBase.Text + "", targetTab);
string jg = MySqlHelper.ExecuteScalar(sql) + "";
if (jg.Equals("2"))
{
//添加标识列
sql = string.Format("alter table {0} add column isSynchro varchar(30);", targetTab);
MySqlHelper.ExecuteNonQuery(sql);
}
//获得需要替换的数据
String replacementValue = synchroSql.Split('^')[2];
string[] replacementValues = replacementValue.Replace(" ", "").Split(',');
//获得修改语句中修改表的数据
String modifyTableColumn = synchroSql.Split('^')[1];
string[] modifyTableColumns = modifyTableColumn.Replace(" ", "").Split(',');
//判断数据源是否有where条件
string conditions = string.Empty;
string isSynchro = string.Empty;
string[] sArray = targetTabSql.Split('^');
if (sArray.Length == 1)
{
isSynchro = " where isSynchro=1";
}
else
{
conditions = " where " + sArray[1];
isSynchro = " where " + sArray[1] + " and isSynchro=1 ";
}
//根据获得对应的表,并把其中的列(isSynchro)变为1
sql = string.Format("update {0} set isSynchro='1' {1}", targetTab, conditions);
MySqlHelper.ExecuteNonQuery(sql);
//根据sql拿到数据源
sql = string.Format("select * from {0}", targetTabSql.Split('^')[0] + isSynchro);
DataTable afkDataSource = MySqlHelper.ExecuteDataTable(sql);
//获得拼接的主键对应条件
string[] synchroSqls = synchroSql.Split('^');
string modifyConditions = string.Empty;//修改sql条件
string[] modifyConditionsReplacementValue = null;//条件中要双方对应的属性
if (synchroSqls.Length == 4)
{
modifyConditions = synchroSqls[3];
modifyConditionsReplacementValue = modifyConditions.Split('=');
}
//获得中间表主键名
// string MysqlPrimaryKey = MysqlGetPrimaryKey(targetTab);
//数据库属性表
DataTable SQLQueryPropertySheet = SqlHelper.ExecuteDataTable(string.Format("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE from information_schema.columns where table_name = '{0}'", mainTableName));
DataTable MYSQLPropertySheet = MySqlHelper.ExecuteDataTable(string.Format("show full columns from {0}", targetTab));
//要执行的sql
string allSql = string.Empty;//主表保存sql
string logAllSql = string.Empty;//日志备份表保存sql
List errorRecordInformation = new List();//报错时需要用到的信息
//List errorRecordInformationMiddle = new List();//报错时需要用到的信息
List DatabaseValidationInformation = new List();//数据库验证信息
RefreshLogUIThread(string.Format("正在同步: lserp >>>>> {0}\r\n", mainTableName));
foreach (DataRow afkitem in afkDataSource.Rows)
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string backupReplaceField = string.Empty;//新增语句列名
string newreplacementValue = string.Empty;//新增语句真实值
string AllBackupReplaceField = string.Empty;//数据源全部列名
string AllBewreplacementValue = string.Empty;//数据源全部真实值
string modifyContent = string.Empty;//修改内容
string newModifyConditions = string.Empty;//主表修改或删除条件
string newModifyConditionsMiddle = string.Empty;//中间表表修改或删除条件
string insertSql = "insert into {0}({1}) values({2});";
string updateSql = "update {0} set {1} {2};";
string ModeOfOperation = "0";//操作编号 1新增,2修改,3删除
if (modifyConditionsReplacementValue != null && modifyConditionsReplacementValue.Length == 2)
{
//当前行主键值
string key = afkitem[modifyConditionsReplacementValue[1].Replace(" ", "")] + "";
newModifyConditions = " where " + modifyConditionsReplacementValue[0] + " ='" + key + "'";
// newModifyConditionsMiddle = " and " + MysqlPrimaryKey + " ='" + afkitem[MysqlPrimaryKey] + "'";
//执行的操作
if (afkDataSource.Columns.Contains("tagid"))
{
ModeOfOperation = afkitem["tagid"] + "";
}
else if (afkDataSource.Columns.Contains("tag_id"))
{
ModeOfOperation = afkitem["tag_id"] + "";
}
else
ModeOfOperation = "0";
//判断LS数据库是否存在这一行
sql = string.Format("select 1 from {0} {1}", mainTableName, newModifyConditions);
bool isExistence = "1".Equals(SqlHelper.ExecuteScalar(sql) + "");
//如果数据库中存在,还是做新增存在的话就不执行
if (isExistence && (ModeOfOperation.Equals("1") || ModeOfOperation.Equals("0")))
{
sql = string.Format("insert into P_RemarkTable(LsTableName,PrimKeyValue,Messages,PrimKey) values ('{0}','{1}','{2}','{3}')", mainTableName, key, "数据库新增已存在相同主键", modifyConditionsReplacementValue[0]);
SqlHelper.ExecuteNonQuery(sql);
continue;
}
}
foreach (DataColumn column in afkDataSource.Columns)
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
if (column.ColumnName.Equals("isSynchro")) continue;
if (column.ColumnName.Equals("directTag")) continue;
string value = afkitem[column.ColumnName.Replace(" ", "")] + "";
value = GetTheRealValue(column, value.Replace("'", "''"));
if (value.Equals("null"))
{
AllBewreplacementValue = AllBewreplacementValue + value + ",";
}
else
{
AllBewreplacementValue = AllBewreplacementValue + "'" + value + "',";
}
AllBackupReplaceField = AllBackupReplaceField + column.ColumnName.Replace(" ", "") + ",";
}
int i = 0;
//重新循环,上面的循环获得的真实值和sql中的字段顺序不同
foreach (string columnName in replacementValues)
{
string name = columnName.Replace(" ", "");
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
if (name.Contains("#add$_"))
{
name = name.Replace("#add$_", "");
if (ModeOfOperation == "2")
{
i++;
continue;
}
}
DataColumn dc = afkDataSource.Columns[name];
string value = afkitem[name] + "";
value = GetTheRealValue(dc, value.Replace("'", "''"));
if (value.Equals("null"))
{
newreplacementValue = newreplacementValue + value + ",";
modifyContent = modifyContent + modifyTableColumns[i].Replace(" ", "") + "=" + value + ",";
}
else
{
newreplacementValue = newreplacementValue + "'" + value + "',";
modifyContent = modifyContent + modifyTableColumns[i].Replace(" ", "") + "='" + value + "',";
}
backupReplaceField = backupReplaceField + modifyTableColumns[i].Replace(" ", "") + ",";
i++;
}
if (ModeOfOperation.Replace(" ", "").Equals("2") && !string.IsNullOrEmpty(newModifyConditions))
{
updateSql = string.Format(updateSql, mainTableName, modifyContent.TrimEnd(','), newModifyConditions);
allSql = allSql + "\r\n" + updateSql + " " + separator;
}
else if (ModeOfOperation.Replace(" ", "").Equals("3") && !string.IsNullOrEmpty(newModifyConditions))
{
string Field = string.Empty;
if (!string.IsNullOrWhiteSpace(disableFieid))
{
Field = disableFieid.Split('^')[0];
updateSql = string.Format(updateSql, mainTableName, Field, newModifyConditions);
allSql = allSql + "\r\n" + updateSql + " " + separator;
}
}
else if (ModeOfOperation.Replace(" ", "").Equals("4") && !string.IsNullOrEmpty(newModifyConditions))
{
string Field = string.Empty;
if (!string.IsNullOrWhiteSpace(disableFieid))
{
Field = disableFieid.Split('^')[1];
updateSql = string.Format(updateSql, mainTableName, Field, newModifyConditions);
allSql = allSql + "\r\n" + updateSql + " " + separator;
}
}
else
{
//获得要添加的列,并新增同步列(“directTag”)
string NewreplacementField = synchroSql.Replace("#add$_", "").Split('^')[1];
insertSql = string.Format(insertSql, mainTableName, NewreplacementField + ",directTag", newreplacementValue + "'1'");
if (!string.IsNullOrWhiteSpace(newModifyConditions))
{
insertSql = insertSql.TrimEnd(';');
insertSql = string.Format(@"if isnull((select 1 from {0} {1}),0)<>1
begin
{2}
end;
", mainTableName, newModifyConditions, insertSql);
}
allSql = allSql + "\r\n" + insertSql + " " + separator;
}
errorRecordInformation.Add(ModeOfOperation.Replace(" ", "") + "^" + newModifyConditions.Replace("where ", ""));
//判断数据是否符合规范
DatabaseValidationInformation.Add(IsValueBlank(SQLQueryPropertySheet, MYSQLPropertySheet, afkitem, modifyTableColumn.Replace("#add$_", ""), replacementValue, DataDirection.AfkToLs));
//写入日志备份表
string backupTableName = string.Empty;//备份表表名
string dateTime = DateTime.Now.ToString();
if (string.IsNullOrWhiteSpace(synLogSql)) continue;
string[] synLog = (item["synLogSql"] + "").Split('^');
string backupSql = "insert into {0}({1}) values({2});";//备份sql
backupSql = string.Format(backupSql, synLog[0], AllBackupReplaceField + synLog[1], AllBewreplacementValue + synLog[2].Replace("GETDATE()", "'" + dateTime + "'"));
logAllSql = logAllSql + "\r\n" + backupSql + " " + separator;
}
try
{
if (!string.IsNullOrWhiteSpace(allSql)) SqlHelper.ExecuteNonQuery(allSql.Replace(separator, ""));
sql = string.Format("update {0} set directTag='2'where directTag ='1'", mainTableName);
SqlHelper.ExecuteNonQuery(sql);
//同步日志
if (!string.IsNullOrWhiteSpace(logAllSql))
{
MySqlHelper.ExecuteNonQuery(logAllSql.Replace(separator, "").Replace("@TransferLogo", "1").Replace("@ErrorType", "null").Replace("@ErrorMessage", "null"));
//sql = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "批量增加,表名:" + mainTableName, "GETDATE()", "正常", "", "朗速");
sql = string.Format("insert into P_RemarkTable(LsTableName,PrimKey) values ('{0}')", targetTab);
SqlHelper.ExecuteNonQuery(sql);
}
//把中间表中同步后的数据删除
sql = string.Format("delete from {0} where isSynchro='1'", targetTab);
if (this.deleteCheck.Checked)
{
MySqlHelper.ExecuteNonQuery(sql);
}
RefreshLogUIThread(string.Format("{0}=========》同步成功:\r\n", mainTableName));
}
catch (Exception ex)
{
string RollBackSql = string.Format("delete {0} where directTag='1'", mainTableName);
SqlHelper.ExecuteNonQuery(RollBackSql);
string[] Sqls = allSql.Split(new string[] { separator }, StringSplitOptions.None);
string[] backupSqls = logAllSql.Split(new string[] { separator }, StringSplitOptions.None);
string operation = string.Empty;
string primaryKey = string.Empty;
//string middlePrimaryKey = string.Empty;
for (int i = 0; i < Sqls.Length - 1; i++)
{
try
{
operation = string.Empty;
primaryKey = string.Empty;
switch (errorRecordInformation[i].Split('^')[0])
{
case "0":
operation = "单条新增";
break;
case "1":
operation = "单条新增";
break;
case "2":
operation = "单条修改";
break;
case "3":
operation = "单条修改";
break;
case "4":
operation = "单条修改";
break;
}
if (!string.IsNullOrWhiteSpace(errorRecordInformation[i].Split('^')[1]))
{
primaryKey = errorRecordInformation[i].Split('^')[1];
//middlePrimaryKey = errorRecordInformationMiddle[i];
}
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
SqlHelper.ExecuteNonQuery(Sqls[i]);
if (Sqls.Length == backupSqls.Length) MySqlHelper.ExecuteNonQuery(backupSqls[i].Replace("@TransferLogo", "1").Replace("@ErrorType", "null").Replace("@ErrorMessage", "null"));
//sql = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", operation + " " + mainTableName + "表,主键" + primaryKey.Replace("'", "''"), "GETDATE()", "正常", "", "朗速");
//sql = string.Format("insert into P_RemarkTable(LsTableName) values ('{0}')", mainTableName);
//SqlHelper.ExecuteNonQuery(sql);
}
catch (Exception newEx)
{
primaryKey = primaryKey.Replace("'", "''");
string errorMessage = string.IsNullOrWhiteSpace(DatabaseValidationInformation[i]) ? newEx.Message.Replace("'", "''") : DatabaseValidationInformation[i];
sql = string.Format("insert into P_RemarkTable(LsTableName,PrimKeyValue,Messages,PrimKey) values ('{0}','{1}','{2}','{3}')", targetTab, primaryKey.Split('=')[1].Replace("'", ""), "朗速获取AFK数据错误:" + errorMessage + "", primaryKey.Split('=')[0]);
SqlHelper.ExecuteNonQuery(sql);
if (Sqls.Length == backupSqls.Length) MySqlHelper.ExecuteNonQuery(backupSqls[i].Replace("@TransferLogo", "2").Replace("@ErrorType", "1").Replace("@ErrorMessage", "'朗速获取AFK数据错误:" + errorMessage + ""));
}
}
sql = string.Format("update {0} set directTag='2'", mainTableName);
SqlHelper.ExecuteNonQuery(sql);
//把中间表中剩下同步失败的数据同步标识改变
sql = string.Format("delete from {0} where isSynchro='1'", targetTab);
if (this.deleteCheck.Checked)
{
MySqlHelper.ExecuteNonQuery(sql);
}
RefreshLogUIThread(string.Format("{0}{1}=========》同步部分失败:\r\n", mainTableName, ex.Message));
}
//执行同步完成后的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
catch (Exception ex)
{
string sql = string.Format("insert into P_RemarkTable(LsTableName,Messages) values ('{0}','{1}')", mainTableName, "朗速获取AFK数据错误:" + ex.Message.Replace("'", "''") + "");
SqlHelper.ExecuteNonQuery(sql);
}
}
}
///
/// 把中间数据库日志表中报错信息存入朗速数据库
///
public void getErrorLine()
{
try
{
DataTable RemarkdockTable = SqlHelper.ExecuteDataTable("select * from Remarkdock");
foreach (DataRow RemarkdockDr in RemarkdockTable.Rows)
{
string LsTableName = RemarkdockDr["LsTableName"] + "";//朗速表名
string ZhTableName = RemarkdockDr["ZhTableName"] + "";//Afk表名
string SucceedId = RemarkdockDr["SucceedId"] + "";//成功标识 1成功 2失败
string SucceedRemark = RemarkdockDr["SucceedRemark"] + "";//错误信息
string PrimKeyId = RemarkdockDr["PrimKeyId"] + "";//afk主键名
string LsPrimKeyId = RemarkdockDr["LsPrimKeyId"] + "";//朗速主键名
//判断有无标识列
string sql = string.Format(@"select CASE when (select count(1)
FROM information_schema.COLUMNS
WHERE table_schema = '{0}'
and table_name = '{1}'
AND column_name = 'Ls_succeed_ID') > 0
then '1'
else '2'
end
", afkDataBase.Text + "", ZhTableName);
string jg = MySqlHelper.ExecuteScalar(sql) + "";
if (jg.Equals("2"))
{
//添加标识列
sql = string.Format("alter table {0} add column Ls_succeed_ID varchar(30);", ZhTableName);
MySqlHelper.ExecuteNonQuery(sql);
}
sql = string.Format("update {0} set Ls_succeed_ID='2' where ifnull(Ls_succeed_ID,'0')!='1' ", ZhTableName);
MySqlHelper.ExecuteNonQuery(sql);
//根据中航的中间日志表名获取没有同步的错误日志信息
string querySql = string.Format("SELECT {0},{1} from {2} where {3}=2 and Ls_succeed_ID='2' ", PrimKeyId, SucceedRemark, ZhTableName, SucceedId);
DataTable queryTable = MySqlHelper.ExecuteDataTable(querySql);
//把获取的错误信息存入朗速数据库表中
string preservationSql = string.Empty;
foreach (DataRow queryDr in queryTable.Rows)
{
preservationSql = string.Format("insert into P_RemarkTable(LsTableName,PrimKeyValue,Messages,PrimKey) values ('{0}','{1}','{2}','{3}')", LsTableName, queryDr[PrimKeyId], (queryDr[SucceedRemark] + "").Replace("'", "''"), LsPrimKeyId);
SqlHelper.ExecuteNonQuery(preservationSql);
}
sql = string.Format("update {0} set Ls_succeed_ID='1' where Ls_succeed_ID='2' ", ZhTableName);
MySqlHelper.ExecuteNonQuery(sql);
}
}
catch (Exception)
{
}
}
///
/// 根据传入的列和值,转成数据库可以获取的值
///
///
///
///
public string GetTheRealValue(DataColumn column, string Value)
{
//如果数据源类型是bool,就替换成0(false)或1(true)
if (column.DataType == typeof(Boolean))
{
if (Value.Equals("true", StringComparison.OrdinalIgnoreCase))
{
Value = "1";
}
else
{
Value = "0";
}
}
if (column.DataType == typeof(int))
{
if (Value.Equals(""))
{
Value = "0";
}
}
if (Value.Equals(""))
{
Value = "null";
}
return Value;
}
//从LS拿数据同步到AFK中
public void getLStoAFK(DataRow[] performDr, bool isRightStop = false)
{
RefreshLogUIThread(string.Format("开始从LS传输数据:\r\n"));
RefreshLogUIThread(string.Format("开始传输:\r\n"));
string targetTab = string.Empty;//获取数据源sql对应的表名(ls数据库表名)
foreach (DataRow item in performDr)
{
try
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string directTagValue = (item["tabname"] + "").Contains("&") ? "8" : "2";//数据源传输成功后更改的directTag的值
string targetTabSql = item["targetTabSql"] + "";//去获得的数据sql
string synchroSql = (item["synchroSql"] + "").ToLower();//同步sql
string synLogSql = (item["synLogSql"] + "").ToLower();//同步到备份日志表中的sql
string afterSql = item["afterSql"] + "";//同步完成后执行的sql
targetTab = targetTabSql.Split('^')[0].Replace(" ", "");
//判断LS数据中有无标识列
string sql = string.Format(@"if not exists(select * from syscolumns
where id=object_id('{0}') and name='directTag')
begin
alter table {0} add directTag int not null default 0
end
", targetTab);
SqlHelper.ExecuteNonQuery(sql);
//中间表表名
string mainTableName = (item["synchroSql"] + "").Split('^')[0].Replace(" ", "");
sql = string.Format(@"select CASE when (select count(1)
FROM information_schema.COLUMNS
WHERE table_schema = '{0}'
and table_name = '{1}'
AND column_name = 'directTag') > 0
then '1'
else '2'
end
", afkDataBase.Text + "", mainTableName);
string jg = MySqlHelper.ExecuteScalar(sql) + "";
if (jg.Equals("2"))
{
//中间表添加标识列
sql = string.Format("alter table {0} add column directTag int;", mainTableName);
MySqlHelper.ExecuteNonQuery(sql);
}
//获得需要替换的数据
String replacementValue = synchroSql.Split('^')[2];
string[] replacementValues = replacementValue.Replace(" ", "").Split(',');
List replacementValuesList = new List(replacementValues);
//判断数据源是否有where条件
string conditions = string.Empty;
string[] sArray = targetTabSql.Split('^');
if (sArray.Length != 1)
{
conditions = " where " + sArray[1];
}
//获得拼接的主键对应条件
string[] synchroSqls = synchroSql.Split('^');
string modifyConditions = string.Empty;//修改sql条件
string[] modifyConditionsReplacementValue = null;//条件中要双方对应的属性
if (synchroSqls.Length == 4)
{
modifyConditions = synchroSqls[3];
modifyConditionsReplacementValue = modifyConditions.Split('=');
}
//是否有对应关联的主表
string relevanceSql = (item["relevanceSql"] + "").ToLower();
string associativeTableName = string.Empty;//相关联的主表
string[] associatedConditions = null;//关联条件
if (!string.IsNullOrWhiteSpace(relevanceSql))
{
associativeTableName = relevanceSql.Split('^')[0];
//第一个为主表字段,第二个为当前表字段
associatedConditions = relevanceSql.Split('^')[1].Split('=');
}
//数据库属性表
DataTable SQLQueryPropertySheet = SqlHelper.ExecuteDataTable(string.Format("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE from information_schema.columns where table_name = '{0}'", targetTab));
DataTable MYSQLPropertySheet = MySqlHelper.ExecuteDataTable(string.Format("show full columns from {0}", mainTableName));
//根据sql拿到数据源
sql = string.Format("select * from {0} {1}", sArray[0], conditions);
DataTable LsDataSource = SqlHelper.ExecuteDataTable(sql);
//要执行的sql
string allSql = string.Empty;//主表保存sql
string logAllSql = string.Empty;//日志备份表保存sql
List errorRecordInformation = new List();//报错时需要用到的信息
string updateAllSql = string.Empty;//保存后修改数据源tagid的全部sql
string modifyTheKey = string.Empty;//修改内容(tagid或tag_id)
string associativeTableSql = string.Empty;//关联表在当前表成功后执行的sql
List DatabaseValidationInformation = new List();//数据库验证信息
RefreshLogUIThread(string.Format("正在传输: lserp >>>>> {0}\r\n", targetTab));
foreach (DataRow afkitem in LsDataSource.Rows)
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string backupReplaceField = string.Empty;
string newreplacementValue = string.Empty;
string insertSql = "insert into {0}({1}) values({2});";
string newModifyConditions = string.Empty;//对应的主键值
string dataSourcePrimaryKey = string.Empty;//数据源主键
string updateTagidSql = "update {0} set {1} {2};";//修改数据源tagid属性sql
if (LsDataSource.Columns.Contains("tagid"))
{
modifyTheKey = "tagid='5'";
}
else if (LsDataSource.Columns.Contains("tag_id"))
{
modifyTheKey = "tag_id='5'";
}
//是否有对应的主表
if (associatedConditions != null && associatedConditions.Length == 2 && !string.IsNullOrWhiteSpace(associativeTableName))
{
sql = string.Format("select directTag from {0} where {1}='{2}'", associativeTableName, associatedConditions[0], afkitem[associatedConditions[1]] + "");
if (!(SqlHelper.ExecuteScalar(sql) + "").Equals("8")) continue;
string updateDirectTagsql = string.Format("update {0} set directTag='2' where {1}='{2}'", associativeTableName, associatedConditions[0], afkitem[associatedConditions[1]] + "");
associativeTableSql = associativeTableSql + "\r\n" + updateDirectTagsql + " " + separator;
}
foreach (DataColumn column in LsDataSource.Columns)
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string value = afkitem[column.ColumnName.Replace(" ", "")] + "";
value = GetTheRealValue(column, value.Replace("'", "''"));
if (modifyConditionsReplacementValue != null && modifyConditionsReplacementValue.Length == 2)
{
if (column.ColumnName.Equals(modifyConditionsReplacementValue[1], StringComparison.OrdinalIgnoreCase))
{
newModifyConditions = " where " + modifyConditionsReplacementValue[0] + " ='" + value + "'";
dataSourcePrimaryKey = " where " + column.ColumnName + " ='" + value + "'";
}
}
int order = Array.IndexOf(replacementValues, column.ColumnName.ToLower());
//保存sql需要用到的真实值
if (order != -1)
{
if (value.Equals("null"))
{
replacementValuesList[order] = value;
}
else
{
replacementValuesList[order] = "'" + value + "'";
}
}
}
newreplacementValue = string.Join(",", replacementValuesList.ToArray());
//获得要添加的列,并新增同步列(“directTag”)
string NewreplacementField = synchroSql.Split('^')[1];
string dateTime = DateTime.Now.ToString();
newreplacementValue = Regex.Replace(newreplacementValue, @"getdate\(\)", "now()", RegexOptions.IgnoreCase);
insertSql = string.Format(insertSql, mainTableName, NewreplacementField + ",directTag", newreplacementValue + ",'1'");
allSql = allSql + "\r\n" + insertSql + " " + separator; ;
updateTagidSql = string.Format(updateTagidSql, targetTab, modifyTheKey, dataSourcePrimaryKey);
updateAllSql = updateAllSql + "\r\n" + updateTagidSql + " " + separator;
errorRecordInformation.Add(newModifyConditions.Replace("where ", ""));
//判断数据是否符合规范
DatabaseValidationInformation.Add(IsValueBlank(SQLQueryPropertySheet, MYSQLPropertySheet, afkitem, replacementValue, NewreplacementField, DataDirection.LsToAfk));
//备份sql
//if (string.IsNullOrWhiteSpace(synLogSql)) continue;
//string backupTableName = string.Empty;//备份表表名
//string[] synLog = (item["synLogSql"] + "").Split('^');
//string backupSql = "insert into {0}({1}) values({2});";//备份sql
//backupSql = string.Format(backupSql, synLog[0], NewreplacementField + "," + synLog[1], newreplacementValue + "," + synLog[2].Replace("GETDATE()", "'" + dateTime + "'"));//Regex.Replace( synLog[2], dateTime, "GETDATE()", RegexOptions.IgnoreCase)
//logAllSql = logAllSql + "\r\n" + backupSql + " " + separator; ;
}
try
{
if (!string.IsNullOrWhiteSpace(allSql))
{
MySqlHelper.ExecuteNonQuery(allSql.Replace(separator, ""));
sql = string.Format("update {0} set directTag='2' where directTag='1'", mainTableName);
MySqlHelper.ExecuteNonQuery(sql);
}
//同步日志
//if (!string.IsNullOrWhiteSpace(logAllSql))
//{
// MySqlHelper.ExecuteNonQuery(logAllSql.Replace(separator, "").Replace("@ErrorType", "null").Replace("@ErrorMessage", "null"));
// sql = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "批量增加,表名:" + mainTableName, "GETDATE()", "正常", "", "AFK");
// SqlHelper.ExecuteNonQuery(sql);
//}
if (!string.IsNullOrWhiteSpace(updateAllSql))
{
//SqlHelper.ExecuteNonQuery(updateAllSql.Replace(separator, ""));
}
if (!string.IsNullOrWhiteSpace(associativeTableSql))
{
SqlHelper.ExecuteNonQuery(associativeTableSql.Replace(separator, ""));
}
sql = string.Format("update {0} set directTag='{2}' {1}", targetTab, conditions, directTagValue);
SqlHelper.ExecuteNonQuery(sql);
RefreshLogUIThread(string.Format("{0}=========》传输成功:\r\n", targetTab));
}
catch (Exception ex)
{
if (!string.IsNullOrWhiteSpace(associativeTableSql))
{
//不管报错先把主表中的directTag改了,单条执行时报错时在改回来
SqlHelper.ExecuteNonQuery(associativeTableSql.Replace(separator, ""));
}
sql = string.Format("delete from {0} where directTag='1'", mainTableName);
MySqlHelper.ExecuteNonQuery(sql);
//string[] logAllSqls = logAllSql.Split(new string[] { separator }, StringSplitOptions.None);
string[] allSqls = allSql.Split(new string[] { separator }, StringSplitOptions.None);
// string[] updatesqls = updateAllSql.Split(new string[] { separator }, StringSplitOptions.None);
string[] associativeTableSqls = associativeTableSql.Split(new string[] { separator }, StringSplitOptions.None);
string primaryKey = string.Empty;//主键值
string RollBackSql = string.Empty;
for (int i = 0; i < allSqls.Length - 1; i++)
{
try
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
if (!string.IsNullOrWhiteSpace(errorRecordInformation[i]))//
{
primaryKey = errorRecordInformation[i];
if (!string.IsNullOrWhiteSpace(conditions))
{
RollBackSql = string.Format("update {0} set directTag='{2}' {1} and {3}", targetTab, conditions, directTagValue, primaryKey.Replace(modifyConditionsReplacementValue[0], modifyConditionsReplacementValue[1]));
SqlHelper.ExecuteNonQuery(RollBackSql);
}
else
{
RollBackSql = string.Format("update {0} set directTag='{2}' {1} where {3}", targetTab, conditions, directTagValue, primaryKey.Replace(modifyConditionsReplacementValue[0], modifyConditionsReplacementValue[1]));
SqlHelper.ExecuteNonQuery(RollBackSql);
}
}
MySqlHelper.ExecuteNonQuery(allSqls[i]);
//if (logAllSqls.Length > i) MySqlHelper.ExecuteNonQuery(logAllSqls[i].Replace("@ErrorType", "null").Replace("@ErrorMessage", "null"));
//SqlHelper.ExecuteNonQuery(updatesqls[i].Replace(separator, ""));
//sql = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + mainTableName + "表,主键" + primaryKey.Replace("'", "''"), "GETDATE()", "正常", "", "AFK");
//SqlHelper.ExecuteNonQuery(sql);
}
catch (Exception newEx)
{
string errorMessage = string.IsNullOrWhiteSpace(DatabaseValidationInformation[i]) ? newEx.Message.Replace("'", "''") : DatabaseValidationInformation[i];
sql = string.Format("insert into P_RemarkTable(LsTableName,PrimKeyValue,Messages,PrimKey) values ('{0}','{1}','{2}','{3}')", mainTableName, primaryKey.Split('=')[1].Replace("'", ""), "AFK获取朗速数据错误:" + errorMessage + "", primaryKey.Split('=')[0]);
SqlHelper.ExecuteNonQuery(sql);
if (!string.IsNullOrWhiteSpace(primaryKey))//
{
if (!string.IsNullOrWhiteSpace(conditions))
{
RollBackSql = string.Format("update {0} set directTag='3' {1} and {2}", targetTab, conditions, primaryKey.Replace(modifyConditionsReplacementValue[0], modifyConditionsReplacementValue[1]));
SqlHelper.ExecuteNonQuery(RollBackSql);
}
else
{
RollBackSql = string.Format("update {0} set directTag='3' {1} where {2}", targetTab, conditions, primaryKey.Replace(modifyConditionsReplacementValue[0], modifyConditionsReplacementValue[1]));
SqlHelper.ExecuteNonQuery(RollBackSql);
}
}
//有对应主表,并且当前明细表的行sql报错,回滚主表directTag值
if (associativeTableSqls.Length > i && !string.IsNullOrWhiteSpace(associativeTableSqls[i]))
{
string[] newAssociatedConditions = associativeTableSqls[i].Split(new string[] { "where" }, StringSplitOptions.None);
sql = string.Format("update {0} set directTag='8' where {1}", associativeTableName, newAssociatedConditions[1]);
SqlHelper.ExecuteNonQuery(sql);
}
//SqlHelper.ExecuteNonQuery(updatesqls[i].Replace(separator, "").Replace("5", "3"));
}
}
if (string.IsNullOrWhiteSpace(modifyConditions))
{
RollBackSql = string.Format("update {0} set directTag='2' {1} ", targetTab, conditions);
SqlHelper.ExecuteNonQuery(RollBackSql);
}
RefreshLogUIThread(string.Format("{0}{1}=========》部分传输失败:\r\n", targetTab, ex.Message));
//修改中间主表中的同步中内容
RollBackSql = string.Format("update {0} set directTag='2' where directTag='1'", mainTableName);
MySqlHelper.ExecuteNonQuery(RollBackSql);
}
//执行同步完成后的sql
if (!string.IsNullOrWhiteSpace(afterSql)) SqlHelper.ExecuteNonQuery(afterSql);
}
catch (Exception ex)
{
string sql = string.Format("insert into P_RemarkTable(LsTableName,Messages) values ('{0}','{1}')", targetTab, "AFK获取朗速数据错误:" + ex.Message.Replace("'", "''") + "");
SqlHelper.ExecuteNonQuery(sql);
}
}
}
#region 测试汇总单条执行方法
///
/// 数据传递方向
///
public enum DataDirection : int
{
LsToAfk = 1,
AfkToLs = 0
}
#region 同步数据单条执行
public void SynchroDataSingle(DataTable synchronousTable, DataDirection dataDirection, bool isRightStop = false)
{
string selectCond = string.Format("directionTag='{0}'", ((int)dataDirection));
DataRow[] performDr = synchronousTable.Select(selectCond);//需要执行的数据条数
RefreshLogUIThread(string.Format("开始从{0}获取数据:\r\n", dataDirection == 0 ? "中航爱福客" : "朗速"));
RefreshLogUIThread(string.Format("开始同步:\r\n"));
foreach (DataRow item in performDr)//循环需要同步的表
{
if (isStop && !isRightStop)
{
RefreshLogUIThread(string.Format("暂停同步……\r\n"));
StopMethod();
}
string[] targetStrs = (item["targetTabSql"] + "").ToLower().Split('^');//数据源字段解析
string[] synchroStrs = (item["synchroSql"] + "").ToLower().Split('^');//同步字段解析
string[] synLogStrs = (item["synLogSql"] + "").ToLower().Split('^');//同步日志表字段解析
string[] primaryKeys = null;
if (synchroStrs.Length == 4)
{
primaryKeys = synchroStrs[3].Replace(" ", "").Split('=');
}
#region 中航方相关信息
string afkTabName = dataDirection == 0 ? targetStrs[0].Replace(" ", "") : synchroStrs[0].Replace(" ", "");//表名
string afkTargeFields = dataDirection == 0 ? synchroStrs[2].Replace(" ", "") : synchroStrs[1].Replace(" ", "");//字段名
string afkPrimaryKey = dataDirection == 0 ? (primaryKeys != null && primaryKeys.Length == 2 ? primaryKeys[1] : "") : (primaryKeys != null && primaryKeys.Length == 2 ? primaryKeys[0] : "");
#endregion
#region 朗速方相关信息
string lsTabName = dataDirection == 0 ? synchroStrs[0].Replace(" ", "") : targetStrs[0].Replace(" ", "");
string lsTargeFields = dataDirection == 0 ? synchroStrs[1].Replace(" ", "") : synchroStrs[2].Replace(" ", "");
string lsPrimaryKey = dataDirection == 0 ? (primaryKeys != null && primaryKeys.Length == 2 ? primaryKeys[0] : "") : (primaryKeys != null && primaryKeys.Length == 2 ? primaryKeys[1] : "");
#endregion
#region 日志表相关信息
string logTabName = synLogStrs.Length == 3 ? synLogStrs[0].Replace(" ", "") : "";
string[] logFields = synLogStrs.Length == 3 ? synLogStrs[1].Replace(" ", "").Split(',') : null;
string[] logAsFields = synLogStrs.Length == 3 ? synLogStrs[2].Replace(" ", "").Split(',') : null;
string logSucceeId = "";
string logErrorType = "";
string logErrorMessage = "";
#endregion
#region 其他信息
string afterSql = (item["afterSql"] + "").ToLower();//同步完成后执行的sql
string disableFieids = (item["disableField"] + "").ToLower();//tagid是3或者4,指定字段改变
//数据库属性表
DataTable SQLQueryPropertySheet = SqlHelper.ExecuteDataTable(string.Format("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE from information_schema.columns where table_name = '{0}'", lsTabName));
DataTable MYSQLPropertySheet = MySqlHelper.ExecuteDataTable(string.Format("show full columns from {0}", afkTabName));
#endregion
int ErrorNumber = 0;
try
{
string lsExistTagStr = string.Format(@"if not exists(select * from syscolumns
where id=object_id('{0}') and name='directTag')
begin
alter table {0} add directTag int
end", lsTabName);
SqlHelper.ExecuteNonQuery(lsExistTagStr);//判断朗速方是否存在同步完成字段
string afkExistTagStr = string.Format(@"select CASE when (select count(1)
FROM information_schema.COLUMNS
WHERE table_schema = '{0}'
and table_name = '{1}'
AND column_name = 'isSynchro') > 0
then '1'
else '2'
end
", afkDataBase.Text + "", afkTabName);
string afkExistResult = MySqlHelper.ExecuteScalar(afkExistTagStr) + "";//判断中航方有无标识列
if (afkExistResult.Equals("2"))
{
string afkAddTagStr = string.Format("alter table {0} add column isSynchro varchar(30);", afkTabName); //如果不存在则添加标识列
MySqlHelper.ExecuteNonQuery(afkAddTagStr);
}
//判断数据源是否有where条件,
string sourceWhereCond = string.Empty;//获取数据源where条件
if (targetStrs.Length == 1)
sourceWhereCond = dataDirection == 0 ? "where isSynchro=1" : " where directTag<>2";//数据源是afk则默认条件字段没有意义,数据源是ls则需获取默认条件字段不为2的数据
else
sourceWhereCond = string.Format(" where {0}", dataDirection == 0 ? targetStrs[1] + " and isSynchro=1 " : targetStrs[1]);
#region 获取数据源
//如果是ls获取数据,要先把数据源中当前的全部数据的isSynchro变为1
if (dataDirection == 0)
{
string conditions = string.Empty;
conditions = targetStrs.Length == 2 ? " where " + targetStrs[1] : "";
string sql = string.Format("update {0} set isSynchro='1' {1}", afkTabName, conditions);
MySqlHelper.ExecuteNonQuery(sql);
}
string sourceTabNale = dataDirection == 0 ? afkTabName : lsTabName;//数据源表名
string getSourceTabName = dataDirection == 0 ? lsTabName : afkTabName;//接受数据表表名
string sourceSelectFields = dataDirection == 0 ? afkTargeFields : lsTargeFields;//数据源字段
if (sourceSelectFields.Contains("getdate()"))//处理各种特殊字段
sourceSelectFields = sourceSelectFields.Replace("getdate()", dataDirection == 0 ? "now() as as_senddate" : "getdate() as as_senddate");
if (sourceSelectFields.Contains("#add$_"))
sourceSelectFields = sourceSelectFields.Replace("#add$_", "");
string selectSourceSql = string.Format("select {0} from {1}{2}", sourceSelectFields, sourceTabNale, sourceWhereCond);//查询数据源sql
DataTable sourceTab = dataDirection == 0 ? MySqlHelper.ExecuteDataTable(selectSourceSql) : SqlHelper.ExecuteDataTable(selectSourceSql);//获取数据源
#endregion
RefreshLogUIThread(string.Format("正在同步: {0} {2} >>>>> {1} {3}\r\n", dataDirection == 0 ? "中航爱福客" : "朗速", dataDirection == 0 ? "朗速" : "中航爱福客", dataDirection == 0 ? afkTabName : lsTabName, dataDirection == 0 ? lsTabName : afkTabName));
string modeOfOperation = sourceTab.Columns.Contains("tagid") ? "tagid" : sourceTab.Columns.Contains("tag_id") ? "tag_id" : "";//获取执方式的字段
string dataTransferSql = "";//执行数据传递sql
string dataTransferLogSql = "";//接收数据需要向中间表写日志
string lsErrorLogSqlStr = "";//朗速日志表
ErrorNumber = 0;
if (!string.IsNullOrEmpty(modeOfOperation))
{
IEnumerable> resultGroup = sourceTab.Rows.Cast().GroupBy(dr => dr[modeOfOperation] + "");//C# 对DataTable中的某列分组,result中的Key是分组后的值
foreach (IGrouping afkTagGroup in resultGroup)//按tagid分组
{
switch (afkTagGroup.Key)
{
case "1"://传递新增
#region 新增
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
bool pushLog = false;
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
//判断是否有不能为空的数据
string SaveErrorMessage = IsValueBlank(SQLQueryPropertySheet, MYSQLPropertySheet, sourceRow, lsTargeFields, afkTargeFields, dataDirection);
if (!string.IsNullOrWhiteSpace(SaveErrorMessage))
{
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = SaveErrorMessage;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
continue;
}
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
if (dataDirection == 0 && IsExistPrimaryValue(sourceRow, getSourceTabName, getSourcePrimaryKey, sourcePrimaryKey, dataDirection))//朗速获取数据前应判断主键是否存在,执行前
{
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = string.Format("主键值{0}已存在", primaryValue);
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", string.Format("主键值{0}已存在", primaryValue), dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
continue;
}
int result = dataDirection == 0 ? SqlHelper.ExecuteNonQuery(dataTransferSql) : MySqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
if (dataDirection == DataDirection.AfkToLs)//接收数据时aftersql判断
{
if (!string.IsNullOrWhiteSpace(afterSql))
{
DataTable afterTab = SqlHelper.ExecuteDataTable(ReplaceRowValue(afterSql, sourceRow));//执行成功失败
string execsql = "";
string type = "";
if (afterTab != null && afterTab.Rows.Count > 0)
{
DataRow afterRow = afterTab.Rows[0];
execsql = afterRow.Table.Columns.Contains("execsql") ? afterRow["execsql"] + "" : "";
type = afterRow.Table.Columns.Contains("type") ? afterRow["type"] + "" : "";
}
string afterReturnMsg = execsql;
if (afterReturnMsg.Equals("Exec_BillOutPush", StringComparison.CurrentCultureIgnoreCase))
{
afterReturnMsg = BillOutPush(sourceRow, type);
if (!string.IsNullOrWhiteSpace(afterSql) && string.IsNullOrEmpty(afterReturnMsg))//返回为空则成功
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
}
else if (!string.IsNullOrWhiteSpace(afterSql) && !string.IsNullOrEmpty(afterReturnMsg))
{
if (afterReturnMsg.Equals("99999"))
{
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = "未检测到明细表数据";
updateIssychro(sourceTabNale, sourcePrimaryKey, sourceRow);
pushLog = true;
continue;
}
logErrorMessage = afterReturnMsg;
logSucceeId = "2";
logErrorType = "1";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
}
}
}
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
//LS》AFK要处理双方数据的directTag问题
if (dataDirection == DataDirection.LsToAfk)
{
//把传输的数据directTag改为2
string sql = string.Format("update {0} set directTag='2' where {1}='{2}'", afkTabName, afkPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
MySqlHelper.ExecuteNonQuery(sql);
//把ls数据库中已经传输的数据directTag改为2
sql = string.Format("update {0} set directTag='2' where {1}='{2}'", lsTabName, lsPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
SqlHelper.ExecuteNonQuery(sql);//插入朗速日志表
}
#region 处理中间表写入日志
if (synLogStrs.Length == 3)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
if (!pushLog)
{
int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
}
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);//插入朗速日志表
#endregion
}
}
#endregion
break;
case "2"://传递修改
#region 修改
if (dataDirection == 0)
{
#region 修改朗速为修改语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertLogKeysStr = "";//insert日志语句keys
string insertLogValuesStr = "";//insert日志语句values
try
{
dataTransferSql = "update {0} set {1} where {2}";
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetUpdateSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, getSourcePrimaryKey, sourcePrimaryKey, out insertLogKeysStr, out insertLogValuesStr, out dataTransferSql);
int result = SqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
if (dataDirection == DataDirection.AfkToLs)//接收数据时aftersql判断
{
if (!string.IsNullOrWhiteSpace(afterSql))
{
DataTable afterTab = SqlHelper.ExecuteDataTable(ReplaceRowValue(afterSql, sourceRow));//执行成功失败
string execsql = "";
string type = "";
if (afterTab != null && afterTab.Rows.Count > 0)
{
DataRow afterRow = afterTab.Rows[0];
execsql = afterRow.Table.Columns.Contains("execsql") ? afterRow["execsql"] + "" : "";
type = afterRow.Table.Columns.Contains("type") ? afterRow["type"] + "" : "";
}
string afterReturnMsg = execsql;
if (afterReturnMsg.Equals("Exec_BillOutPush", StringComparison.CurrentCultureIgnoreCase))
{
afterReturnMsg = BillOutPush(sourceRow, type);
if (!string.IsNullOrWhiteSpace(afterSql) && string.IsNullOrEmpty(afterReturnMsg))//返回为空则成功
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
}
else if (!string.IsNullOrWhiteSpace(afterSql) && !string.IsNullOrEmpty(afterReturnMsg))
{
logErrorMessage = afterReturnMsg;
logSucceeId = "2";
logErrorType = "1";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
}
}
}
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
#region 处理中间表写入日志
if (synLogStrs.Length == 3 && dataDirection == 0)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertLogKeysStr, insertLogValuesStr, logTabName, out dataTransferLogSql);
int logResult = MySqlHelper.ExecuteNonQuery(dataTransferLogSql);
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);
#endregion
}
}
#endregion
}
else
{
#region 修改爱福客为新增语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
int result = MySqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
// lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
//LS》AFK要处理双方数据的directTag问题
//把传输的数据directTag改为2
string sql = string.Format("update {0} set directTag='2' where {1}='{2}'", afkTabName, afkPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
MySqlHelper.ExecuteNonQuery(sql);
//把ls数据库中已经传输的数据directTag改为2
sql = string.Format("update {0} set directTag='2' where {1}='{2}'", lsTabName, lsPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
SqlHelper.ExecuteNonQuery(sql);//插入朗速日志表
#region 处理中间表写入日志,向爱福客插入数据不需向中间表添加日志
//string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
//GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
//int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr); //插入朗速日志表
#endregion
}
}
#endregion
}
#endregion
break;
case "3"://更改状态,禁用,上下架等
#region 更改状态,禁用,上下架等
if (dataDirection == 0)
{
#region 修改朗速为修改语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertLogKeysStr = "";//insert日志语句keys
string insertLogValuesStr = "";//insert日志语句values
string[] disableFieidsArgs = disableFieids.Replace(" ", "").Split('^');
string stateField = disableFieidsArgs[0];//3对应第一个状态
try
{
dataTransferSql = "update {0} set {1} where {2}";
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetChangeStateSqlStr(sourceRow, stateField, getSourceKeys, afkTargeFields, getSourceTabName, getSourcePrimaryKey, sourcePrimaryKey, out insertLogKeysStr, out insertLogValuesStr, out dataTransferSql);
int result = SqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
if (dataDirection == DataDirection.AfkToLs)//接收数据时aftersql判断
{
if (!string.IsNullOrWhiteSpace(afterSql))
{
DataTable afterTab = SqlHelper.ExecuteDataTable(ReplaceRowValue(afterSql, sourceRow));//执行成功失败
string execsql = "";
string type = "";
if (afterTab != null && afterTab.Rows.Count > 0)
{
DataRow afterRow = afterTab.Rows[0];
execsql = afterRow.Table.Columns.Contains("execsql") ? afterRow["execsql"] + "" : "";
type = afterRow.Table.Columns.Contains("type") ? afterRow["type"] + "" : "";
}
string afterReturnMsg = execsql;
if (afterReturnMsg.Equals("Exec_BillOutPush", StringComparison.CurrentCultureIgnoreCase))
{
afterReturnMsg = BillOutPush(sourceRow, type);
if (!string.IsNullOrWhiteSpace(afterSql) && string.IsNullOrEmpty(afterReturnMsg))//返回为空则成功
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
}
else if (!string.IsNullOrWhiteSpace(afterSql) && !string.IsNullOrEmpty(afterReturnMsg))
{
logErrorMessage = afterReturnMsg;
logSucceeId = "2";
logErrorType = "1";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
}
}
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
}
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
#region 处理中间表写入日志
if (synLogStrs.Length == 3)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertLogKeysStr, insertLogValuesStr, logTabName, out dataTransferLogSql);
#endregion
int logResult = MySqlHelper.ExecuteNonQuery(dataTransferLogSql);
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);
}
}
#endregion
}
else
{
#region 修改爱福客为新增语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
int result = MySqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
//LS》AFK要处理双方数据的directTag问题
//把传输的数据directTag改为2
string sql = string.Format("update {0} set directTag='2' where {1}='{2}'", afkTabName, afkPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
MySqlHelper.ExecuteNonQuery(sql);
//把ls数据库中已经传输的数据directTag改为2
sql = string.Format("update {0} set directTag='2' where {1}='{2}'", lsTabName, lsPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
SqlHelper.ExecuteNonQuery(sql);//插入朗速日志表
#region 处理中间表写入日志,向爱福客插入数据不需向中间表添加日志
//string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
//GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
//int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr); //插入朗速日志表
#endregion
}
}
#endregion
}
#endregion
break;
case "4":
#region 更改状态,禁用,上下架等
if (dataDirection == 0)
{
#region 修改朗速为修改语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertLogKeysStr = "";//insert日志语句keys
string insertLogValuesStr = "";//insert日志语句values
string[] disableFieidsArgs = disableFieids.Replace(" ", "").Split('^');
string stateField = disableFieidsArgs[1];//4对应第二个状态
try
{
dataTransferSql = "update {0} set {1} where {2}";
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetChangeStateSqlStr(sourceRow, stateField, getSourceKeys, afkTargeFields, getSourceTabName, getSourcePrimaryKey, sourcePrimaryKey, out insertLogKeysStr, out insertLogValuesStr, out dataTransferSql);
int result = SqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
if (dataDirection == DataDirection.AfkToLs)//接收数据时aftersql判断
{
if (!string.IsNullOrWhiteSpace(afterSql))
{
DataTable afterTab = SqlHelper.ExecuteDataTable(ReplaceRowValue(afterSql, sourceRow));//执行成功失败
string execsql = "";
string type = "";
if (afterTab != null && afterTab.Rows.Count > 0)
{
DataRow afterRow = afterTab.Rows[0];
execsql = afterRow.Table.Columns.Contains("execsql") ? afterRow["execsql"] + "" : "";
type = afterRow.Table.Columns.Contains("type") ? afterRow["type"] + "" : "";
}
string afterReturnMsg = execsql;
if (afterReturnMsg.Equals("Exec_BillOutPush", StringComparison.CurrentCultureIgnoreCase))
{
afterReturnMsg = BillOutPush(sourceRow, type);
if (!string.IsNullOrWhiteSpace(afterSql) && string.IsNullOrEmpty(afterReturnMsg))//返回为空则成功
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
}
else if (!string.IsNullOrWhiteSpace(afterSql) && !string.IsNullOrEmpty(afterReturnMsg))
{
logErrorMessage = afterReturnMsg;
logSucceeId = "2";
logErrorType = "1";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
}
}
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
}
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
#region 处理中间表写入日志
if (synLogStrs.Length == 3)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertLogKeysStr, insertLogValuesStr, logTabName, out dataTransferLogSql);
#endregion
int logResult = MySqlHelper.ExecuteNonQuery(dataTransferLogSql);
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);
}
}
#endregion
}
else
{
#region 修改爱福客为新增语句
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
int result = MySqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
// lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条修改" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
//LS》AFK要处理双方数据的directTag问题
//把传输的数据directTag改为2
string sql = string.Format("update {0} set directTag='2' where {1}='{2}'", afkTabName, afkPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
MySqlHelper.ExecuteNonQuery(sql);
//把ls数据库中已经传输的数据directTag改为2
sql = string.Format("update {0} set directTag='2' where {1}='{2}'", lsTabName, lsPrimaryKey, sourceRow[lsPrimaryKey.Trim()]);
SqlHelper.ExecuteNonQuery(sql);//插入朗速日志表
#region 处理中间表写入日志,向爱福客插入数据不需向中间表添加日志
//string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
//GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
//int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr); //插入朗速日志表
#endregion
}
}
#endregion
}
#endregion
break;
case ""://没有可执行的操作
#region 没有可执行的操作
foreach (DataRow sourceRow in afkTagGroup)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = string.Format("{0}为空,没有可执行的操作", modeOfOperation);
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", string.Format("{0}为空,没有可执行的操作", modeOfOperation), dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
#region 处理中间表写入日志
if (synLogStrs.Length == 3)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);//插入朗速日志表
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);
#endregion
}
}
#endregion
break;
}
}
}
else
{
#region 没有标识字段默认新增
foreach (DataRow sourceRow in sourceTab.Rows)
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
lsErrorLogSqlStr = "";
string getSourcePrimaryKey = dataDirection == 0 ? lsPrimaryKey : afkPrimaryKey;
string sourcePrimaryKey = dataDirection == 0 ? afkPrimaryKey : lsPrimaryKey;
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeysStr = "";//insert语句keys
string insertValuesStr = "";//insert语句values
try
{
string getSourceKeys = dataDirection == 0 ? lsTargeFields : afkTargeFields;//接收数据表字段
GetInsertSqlStr(sourceRow, getSourceKeys, afkTargeFields, getSourceTabName, out insertKeysStr, out insertValuesStr, out dataTransferSql, dataDirection);
int result = dataDirection == 0 ? SqlHelper.ExecuteNonQuery(dataTransferSql) : MySqlHelper.ExecuteNonQuery(dataTransferSql);
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";//执行成功
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue) values ('{0}','{1}','{2}')", afkTabName, afkPrimaryKey, primaryValue);
if (dataDirection == DataDirection.AfkToLs)//接收数据时aftersql判断
{
if (!string.IsNullOrWhiteSpace(afterSql))
{
DataTable afterTab = SqlHelper.ExecuteDataTable(ReplaceRowValue(afterSql, sourceRow));//执行成功失败
string execsql = "";
string type = "";
if (afterTab != null && afterTab.Rows.Count > 0)
{
DataRow afterRow = afterTab.Rows[0];
execsql = afterRow.Table.Columns.Contains("execsql") ? afterRow["execsql"] + "" : "";
type = afterRow.Table.Columns.Contains("type") ? afterRow["type"] + "" : "";
}
string afterReturnMsg = execsql;
if (afterReturnMsg.Equals("Exec_BillOutPush", StringComparison.CurrentCultureIgnoreCase))
{
afterReturnMsg = BillOutPush(sourceRow, type);
if (!string.IsNullOrWhiteSpace(afterSql) && string.IsNullOrEmpty(afterReturnMsg))//返回为空则成功
{
logSucceeId = "1";
logErrorType = "0";
logErrorMessage = "";
}
else if (!string.IsNullOrWhiteSpace(afterSql) && !string.IsNullOrEmpty(afterReturnMsg))
{
logErrorMessage = afterReturnMsg;
logSucceeId = "2";
logErrorType = "1";
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
}
}
// lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "正常", "", dataDirection == 0 ? "朗速" : "中航爱福客");
}
}
catch (Exception ex)
{
ErrorNumber++;
logSucceeId = "2";
logErrorType = "1";
logErrorMessage = ex.Message.Replace("'", "''");
//lsErrorLogSqlStr = string.Format("Insert into ls_errlogtab(Ls_log_tagid,Ls_log_opdt,Ls_log_rulst,Ls_log_buginfo,Ls_log_coname)values('{0}',{1},'{2}','{3}','{4}')", "单条增加" + getSourceTabName + "表,主键" + getSourcePrimaryKey.Replace("'", "''"), "GETDATE()", "异常", ex.Message, dataDirection == 0 ? "朗速" : "中航爱福客");
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, logErrorMessage);
}
finally
{
#region 处理中间表写入日志
if (synLogStrs.Length == 3)
{
try
{
string[] logArgs = new string[] { logSucceeId, logErrorType, logErrorMessage };
GetLogSqlStr(logFields, logAsFields, logArgs, insertKeysStr, insertValuesStr, logTabName, out dataTransferLogSql);
int logResult = dataDirection == 0 ? MySqlHelper.ExecuteNonQuery(dataTransferLogSql) : 0;
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);//插入朗速日志表
}
catch (Exception ex)
{
ErrorNumber++;
lsErrorLogSqlStr = string.Format("insert into P_RemarkTable(LsTableName,PrimKey,PrimKeyValue,Messages) values ('{0}','{1}','{2}','{3}')", afkTabName, afkPrimaryKey, primaryValue, ex.Message.Replace("'", "''"));
}
SqlHelper.ExecuteNonQuery(lsErrorLogSqlStr);
}
#endregion
}
}
#endregion
}
//删除
if (dataDirection == 0)
{
string deleteSql = string.Format("delete from {0} where isSynchro='1'", afkTabName);
if (this.deleteCheck.Checked)
{
MySqlHelper.ExecuteNonQuery(deleteSql);
}
}
}
catch (Exception ex)
{
string direction = dataDirection == 0 ? "朗速获取AFK数据错误" : "AFK获取朗速数据错误";
string sql = string.Format("insert into P_RemarkTable(LsTableName,Messages) values ('{0}','{1}')", lsTabName, direction + ":" + ex.Message.Replace("'", "''") + "");
SqlHelper.ExecuteNonQuery(sql);
}
finally
{
RefreshLogUIThread("同步完成,失败条数:" + ErrorNumber + "\r\n");
}
}
}
#endregion
#region MyRegion
private void updateIssychro(string dataName, string primary, DataRow sourceRow)
{
string primaryValue = !string.IsNullOrEmpty(primary) ? sourceRow[primary] + "" : "";
string sql = "update {0} set issynchro ='0' where {1}='{2}'";
sql = string.Format(sql, dataName, primary, primaryValue);
MySqlHelper.ExecuteNonQuery(sql);
}
#endregion
#region 反写固定存储过程些入出库单
///
/// 反写固定存储过程些入出库单
///
/// 数据行中name字段
/// 数据行中logisticsid字段
///
public static string BillOutPush(DataRow sourceRow, string type)
{
string name = sourceRow.Table.Columns.Contains("name") ? sourceRow["name"] + "" : "";
string logisticsid = sourceRow.Table.Columns.Contains("logisticsid") ? sourceRow["logisticsid"] + "" : "";
string operatorName = "管理员", operatorId = "1";
if (!string.IsNullOrEmpty(name))
{
string sql = string.Format("select employeeid,employeename from p_employeetab where employeename = '{0}'", name);
DataTable DataOperTable = SqlHelperOther.ExecuteDataTable(sql);
if (DataOperTable.Rows.Count > 0)
{
operatorId = DataOperTable.Rows[0]["employeeid"] + "";
operatorName = DataOperTable.Rows[0]["employeename"] + "";
}
}
SqlParameter msg = new SqlParameter("@msg", SqlDbType.VarChar, 3000);
msg.Direction = ParameterDirection.Output;
List list = new List
{
new SqlParameter("@nbgys",SqlDbType.VarChar,10),
new SqlParameter("@type",SqlDbType.Int,4),
new SqlParameter("@keyvalue",SqlDbType.VarChar,200),
new SqlParameter("@operatorId",SqlDbType.Int,4),
new SqlParameter("@operatorName",SqlDbType.VarChar,20),
msg,
};
SqlParameter[] param = list.ToArray();
param[0].Value = "e25d5dd2b4b74dd99f79227d8db5b4c7";
param[1].Value = type;
param[2].Value = logisticsid;
param[3].Value = operatorId;
param[4].Value = operatorName;
param[5].Value = "";
try
{
SqlHelper.ExecuteDataSet(CommandType.StoredProcedure, "wms_createbillpr", "billpr", param);
}
catch (Exception)
{
return msg.Value + "";
}
return msg.Value + "";
}
#endregion
#region 判断主键值是否已经存在
private bool IsExistPrimaryValue(DataRow sourceRow, string getSourceTabName, string getSourcePrimaryKey, string sourcePrimaryKey, DataDirection dataDirection)
{
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
if (!string.IsNullOrEmpty(primaryValue))
{
string isExistSql = string.Format("select * from {0} where {1}='{2}'", getSourceTabName, getSourcePrimaryKey, primaryValue);
DataTable resultTab = new DataTable();
if (dataDirection == 0)
resultTab = SqlHelper.ExecuteDataTable(isExistSql);
else
resultTab = MySqlHelper.ExecuteDataTable(isExistSql);
if (resultTab.Rows.Count > 0)
return true;
else
return false;
}
else
return false;
}
#endregion
#region 判断值是否可以为空
//sql表格属性表 mysql表格属性表 行数据 ls数据库中的列 afk列 方向
private string IsValueBlank(DataTable SQLQueryPropertySheet, DataTable MYSQLPropertySheet, DataRow sourceRow, string LsColumnName, string AfkColumnName, DataDirection dataDirection)
{
string key = string.Empty;
string Value = string.Empty;
string SaveErrorMessage = string.Empty;//提示信息
//判断存入的值是否为空
string[] LsColumnNames = LsColumnName.Split(',');
string[] AfkColumnNames = AfkColumnName.Split(',');
for (int i = 0; i < AfkColumnNames.Length - 1; i++)
{
//获取数据源中当前列名
key = (dataDirection == 0) ? (AfkColumnNames[i] + "").Trim() : (LsColumnNames[i] + "").Trim();
if (key.Contains("getdate()")) continue;
//获取AFK列名或注释
DataRow[] ListOfAttributes = MYSQLPropertySheet.Select("Field='" + (AfkColumnNames[i] + "").Trim() + "'");
string name = AfkColumnNames[i];
if ((!string.IsNullOrWhiteSpace(ListOfAttributes[0]["Comment"] + "")) && (ListOfAttributes[0]["Comment"] + "").Length < 5)
{
name = ListOfAttributes[0]["Comment"] + "";
}
//当前列的值
Value = sourceRow[key] + "";
//判断是否为空
if (dataDirection == 0)
{
SaveErrorMessage += DatabaseFormatJudgment.SQLQueryVerification(SQLQueryPropertySheet, (LsColumnNames[i] + "").Trim(), Value, name);
}
else
{
SaveErrorMessage += DatabaseFormatJudgment.MYSqlVerification(MYSQLPropertySheet, (AfkColumnNames[i] + "").Trim(), Value, name);
}
}
return SaveErrorMessage;
}
#endregion
#region 获取insert语句
private void GetInsertSqlStr(DataRow sourceRow, string getSourceKeys, string afkTargeFields, string getSourceTabName, out string insertKeysStr, out string insertValuesStr, out string dataTransferSql, DataDirection dataDirection)
{
string insertKeys = "";
string insertValues = "";
string afkTargeFieldKey = "";
string insertSql = "insert into {0} ({1}) values ({2})";
string[] getSourceKeysList = getSourceKeys.Split(',');
string[] afkTargeFieldsList = afkTargeFields.Split(',');
for (int i = 0; i < sourceRow.Table.Columns.Count; i++)//循环拼接insert语句
{
string intermediateLogKey = afkTargeFieldsList[i];
string getSourceKey = getSourceKeysList[i];
string sourceKey = sourceRow.Table.Columns[i].ColumnName;
string sourceValue = sourceRow[sourceKey] + "";
if (sourceValue.Contains("'"))
sourceValue = sourceValue.Replace("'", "''");
sourceValue = GetTheRealValue(sourceRow.Table.Columns[i], sourceValue);//转换某些特殊值
if (getSourceKey.Contains("#add$_"))
{
getSourceKey = getSourceKey.Replace("#add$_", "");
afkTargeFieldKey = afkTargeFieldKey.Replace("#add$_", "");
}
insertKeys += string.Format("{0},", getSourceKey);
afkTargeFieldKey += string.Format("{0},", intermediateLogKey);
insertValues += sourceValue.Equals("null") ? string.Format("{0},", sourceValue) : string.Format("'{0}',", sourceValue);
}
insertKeysStr = afkTargeFieldKey;
insertValuesStr = insertValues;
//dataTransferSql = string.Format(insertSql, getSourceTabName, insertKeys.TrimEnd(','), insertValues.TrimEnd(','));
dataTransferSql = dataDirection == 0 ? string.Format(insertSql, getSourceTabName, insertKeys + "directTag", insertValues + "2") : string.Format(insertSql, getSourceTabName, insertKeys.TrimEnd(','), insertValues.TrimEnd(','));
}
#endregion
#region 获取update语句
private void GetUpdateSqlStr(DataRow sourceRow, string getSourceKeys, string afkTargeFields, string getSourceTabName, string getSourcePrimaryKey, string sourcePrimaryKey, out string insertLogKeysStr, out string insertLogValuesStr, out string dataTransferSql)
{
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeys = "";
string insertValues = "";
string updateKeyValues = "";
string afkTargeFieldKey = "";
string updateSql = "update {0} set {1} where {2}";
string[] getSourceKeysList = getSourceKeys.Split(',');
string[] afkTargeFieldsList = afkTargeFields.Split(',');
for (int i = 0; i < sourceRow.Table.Columns.Count; i++)//循环拼接insert语句
{
string getSourceKey = getSourceKeysList[i];
string intermediateLogKey = afkTargeFieldsList[i];
string sourceKey = sourceRow.Table.Columns[i].ColumnName;
string sourceValue = sourceRow[sourceKey] + "";
if (sourceValue.Contains("'"))
sourceValue = sourceValue.Replace("'", "''");
sourceValue = GetTheRealValue(sourceRow.Table.Columns[i], sourceValue);//转换某些特殊值
if (getSourceKey.Contains("#add$_"))
{
afkTargeFieldKey += string.Format("{0},", intermediateLogKey);
insertKeys += string.Format("{0},", getSourceKey);
insertValues += sourceValue.Equals("null") ? string.Format("{0},", sourceValue) : string.Format("'{0}',", sourceValue);
continue;
}
updateKeyValues += sourceValue.Equals("null") ? string.Format("{0}={1},", getSourceKey, sourceValue) : string.Format("{0}='{1}',", getSourceKey, sourceValue);
afkTargeFieldKey += string.Format("{0},", intermediateLogKey);
insertKeys += string.Format("{0},", getSourceKey);
insertValues += sourceValue.Equals("null") ? string.Format("{0},", sourceValue) : string.Format("'{0}',", sourceValue);
}
insertLogKeysStr = afkTargeFieldKey;
insertLogValuesStr = insertValues;
string updateCond = string.Format("{0}='{1}'", getSourcePrimaryKey, primaryValue);
dataTransferSql = string.Format(updateSql, getSourceTabName, updateKeyValues.TrimEnd(','), updateCond);
}
#endregion
#region 获取改变状态语句
private void GetChangeStateSqlStr(DataRow sourceRow, string stateFieid, string getSourceKeys, string afkTargeFields, string getSourceTabName, string getSourcePrimaryKey, string sourcePrimaryKey, out string insertLogKeysStr, out string insertLogValuesStr, out string dataTransferSql)
{
string primaryValue = !string.IsNullOrEmpty(sourcePrimaryKey) ? sourceRow[sourcePrimaryKey] + "" : "";
string insertKeys = "";
string insertValues = "";
string afkTargeFieldKey = "";
string updateSql = "update {0} set {1} where {2}";
string[] getSourceKeysList = getSourceKeys.Split(',');
string[] afkTargeFieldsList = afkTargeFields.Split(',');
for (int i = 0; i < sourceRow.Table.Columns.Count; i++)//循环拼接insert语句
{
string getSourceKey = getSourceKeysList[i];
string intermediateLogKey = afkTargeFieldsList[i];
string sourceKey = sourceRow.Table.Columns[i].ColumnName;
string sourceValue = sourceRow[sourceKey] + "";
if (sourceValue.Contains("'"))
sourceValue = sourceValue.Replace("'", "''");
sourceValue = GetTheRealValue(sourceRow.Table.Columns[i], sourceValue);//转换某些特殊值
if (getSourceKey.Contains("#add$_"))
getSourceKey = getSourceKey.Replace("#add$_", "");
if (intermediateLogKey.Contains("#add$_"))
intermediateLogKey = intermediateLogKey.Replace("#add$_", "");
afkTargeFieldKey += string.Format("{0},", intermediateLogKey);
insertKeys += string.Format("{0},", getSourceKey);
insertValues += sourceValue.Equals("null") ? string.Format("{0},", sourceValue) : string.Format("'{0}',", sourceValue);
}
insertLogKeysStr = afkTargeFieldKey;
insertLogValuesStr = insertValues;
string updateCond = string.Format("{0}='{1}'", getSourcePrimaryKey, primaryValue);
dataTransferSql = string.Format(updateSql, getSourceTabName, stateFieid, updateCond);
}
#endregion
#region 获取logInsert语句
private void GetLogSqlStr(string[] logFields, string[] logAsFields, string[] logArgs, string insertKeysStr, string insertValuesStr, string logTabName, out string dataTransferLogSql)
{
string insertLogKeys = insertKeysStr;
string insertLogValues = insertValuesStr;
string logSqlStr = "insert into {0} ({1}) values ({2})";
for (int i = 0; i < logAsFields.Length; i++)
{
string logField = logFields[i];
string logAsField = logAsFields[i];
insertLogKeys += string.Format("{0},", logField);
if (logAsField.Equals("getdate()", StringComparison.OrdinalIgnoreCase))
insertLogValues += string.Format("{0},", "now()");
else if (logAsField.Equals("@transferLogo", StringComparison.OrdinalIgnoreCase))
insertLogValues += string.Format("'{0}',", logArgs[0]);
else if (logAsField.Equals("@errortype", StringComparison.OrdinalIgnoreCase))
insertLogValues += string.Format("'{0}',", logArgs[1]);
else if (logAsField.Equals("@errormessage", StringComparison.OrdinalIgnoreCase))
insertLogValues += string.Format("'{0}',", logArgs[2]);
else
insertLogValues += string.Format("{0},", "null");
}
dataTransferLogSql = string.Format(logSqlStr, logTabName, insertLogKeys.TrimEnd(','), insertLogValues.TrimEnd(','));
}
#endregion
#region 替换行数据
public string ReplaceRowValue(string defaultValue, DataRow row)
{
if (!string.IsNullOrWhiteSpace(defaultValue))
{
var paramList = GetParamFields(defaultValue);
foreach (string item in paramList)
{
string field = item.Replace("}", "").Replace("{", "").ToLower();
string value = row.Table.Columns.Contains(field) ? row[field] + "" : "";
defaultValue = defaultValue.Replace(item, value);
}
}
return defaultValue;
}
public List GetParamFields(string defaultValue)
{
List list = new List();
Regex regex = new Regex("{([^{])+}");
MatchCollection mcs = regex.Matches(defaultValue);
foreach (Match item in mcs)
{
if (list.IndexOf(item.Value) == -1)
list.Add(item.Value);
}
return list;
}
#endregion
#endregion
///
/// 说明:获取中间表的主键值,没有就创建标识列
/// 创建人:
/// 创建日期:
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
///
public static string MysqlGetPrimaryKey(string TableName)
{
string PrimaryKeyName = string.Empty;
string sql = string.Format(" SHOW KEYS FROM {0} WHERE Key_name = 'PRIMARY'", TableName);
DataTable dt = MySqlHelper.ExecuteDataTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
PrimaryKeyName = dt.Rows[0]["Column_name"] + "";
}
if (string.IsNullOrWhiteSpace(PrimaryKeyName))
{
//没有主键就创建自增长列
sql = string.Format(@"alter table {0} add AutoPrimaryKey BIGINT;
alter table {0} change AutoPrimaryKey AutoPrimaryKey BIGINT not null auto_increment primary key; ", TableName);
MySqlHelper.ExecuteNonQuery(sql);
PrimaryKeyName = "AutoPrimaryKey";
}
return PrimaryKeyName;
}
///
/// 说明:获取表的主键值
/// 创建人:王一帆
/// 创建日期:2020-05-07
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
///
public static string GetPrimaryKey(string TableName)
{
string sqlValue = string.Format("SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='{0}'", TableName);
DataTable dtTable = SqlHelper.ExecuteDataTable(sqlValue);
return (dtTable.Rows.Count > 0) ? dtTable.Rows[0]["COLUMN_NAME"] + "" : string.Empty;
}
///
/// 暂停方法监测
///
public void StopMethod()
{
if (isStop)
{
System.Threading.Thread.Sleep(1000);
StopMethod();
}
}
///
/// 主线程刷新数据
///
///
public void RefreshLog(string msg)
{
txtLog.Text += msg;
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}
///
/// 后台线程刷新数据
///
///
public void RefreshLogUIThread(string msg)
{
Invoke((EventHandler)delegate
{
if (msg.Equals("清空"))
{
txtLog.Clear();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}
else
{
txtLog.Text += msg;
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}
});
}
#region 连接朗速服务器
///
/// 说明:连接服务器
/// 创建人:龚宇超
/// 创建日期:2017-08-09
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// if set to true [is save].
public bool ConnectServer(bool isSave = false)
{
string serverName = this.lsSeverId.Text.Trim();//地址
string dbName = this.lsDataBase.Text.Trim();//数据库名
string user = this.lsName.Text.Trim();//用户名
string password = this.lsPassword.Text.Trim();//密码
if (string.IsNullOrWhiteSpace(serverName))
{
MessageUtil.Show("请重新输入朗速数据库地址");
return false;
}
if (string.IsNullOrWhiteSpace(dbName))
{
MessageUtil.Show("请重新输入朗速数据库库名");
return false;
}
if (string.IsNullOrWhiteSpace(user))
{
MessageUtil.Show("请重新输入朗速数据库用户名");
return false;
}
// 测试数据库连接
try
{
if (ConnectingToDatabase())
{
if (isSave)
{
}
else
{
IniHelper.Write("LS", "serverName", serverName);
IniHelper.Write("LS", "dbName", dbName);
IniHelper.Write("LS", "user", user);
IniHelper.Write("LS", "password", password);
RefreshLogUIThread(DateTime.Now + "朗速数据库连接成功.\r\n");
return true;
}
}
else
{
MessageUtil.Show("连接失败,请检查朗速方配置");
return false;
}
}
catch (Exception ex)
{
MessageUtil.Show("连接失败,请检查朗速方配置");
}
return true;
}
///
/// 说明:连接服务器
/// 创建人:龚宇超
/// 创建日期:2017-08-09
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// if set to true [is save].
public bool ConnectServerOther(bool isSave = false)
{
string serverName = this.lsSeverId.Text.Trim();//地址
string dbName = this.lsDataBase.Text.Trim();//数据库名
string user = this.lsName.Text.Trim();//用户名
string password = this.lsPassword.Text.Trim();//密码
if (string.IsNullOrWhiteSpace(serverName))
{
MessageUtil.Show("请重新输入朗速数据库地址");
return false;
}
if (string.IsNullOrWhiteSpace(dbName))
{
MessageUtil.Show("请重新输入朗速数据库库名");
return false;
}
if (string.IsNullOrWhiteSpace(user))
{
MessageUtil.Show("请重新输入朗速数据库用户名");
return false;
}
// 测试数据库连接
try
{
if (ConnectingToDatabaseOther())
{
if (isSave)
{
}
else
{
IniHelper.Write("LS", "serverName", serverName);
IniHelper.Write("LS", "dbName", dbName);
IniHelper.Write("LS", "user", user);
IniHelper.Write("LS", "password", password);
return true;
}
}
else
{
MessageUtil.Show("连接失败,请检查朗速方配置");
return false;
}
}
catch (Exception ex)
{
MessageUtil.Show("连接失败,请检查朗速方配置");
}
return true;
}
///
/// 说明:创建数据库连接
/// 创建人:龚宇超
/// 创建日期:2017-08-07
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// true if XXXX, false otherwise.
public bool ConnectingToDatabase()
{
string connStr = GetConnection();
if (SqlHelper._connection != null)
{
try
{
SqlHelper._connection.Close();
SqlHelper._connection.Dispose();
}
catch (Exception)
{
}
SqlHelper._connection = null;
}
try
{
SqlHelper._connection = new SqlConnection(connStr);
SqlHelper._connection.Open();
return true;
}
catch (Exception ex)
{
// LogHelper.Instance.WriteLog(ex.Message);
}
return false;
}
///
/// 说明:创建数据库连接
/// 创建人:龚宇超
/// 创建日期:2017-08-07
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// true if XXXX, false otherwise.
public bool ConnectingToDatabaseOther()
{
string connStr = GetConnection();
if (SqlHelperOther._connection != null)
{
try
{
SqlHelperOther._connection.Close();
SqlHelperOther._connection.Dispose();
}
catch (Exception)
{
}
SqlHelperOther._connection = null;
}
try
{
SqlHelperOther._connection = new SqlConnection(connStr);
SqlHelperOther._connection.Open();
return true;
}
catch (Exception ex)
{
// LogHelper.Instance.WriteLog(ex.Message);
}
return false;
}
///
/// 获取连接服务器的字符串
///
///
public string GetConnection()
{
return string.Format("Server={0};Database={1};Persist Security Info=True;User ID={2};Password={3};Connection Timeout=5;MultipleActiveResultSets=true", lsSeverId.Text + "", lsDataBase.Text + "", lsName.Text + "", lsPassword.Text + "");
}
#endregion
#region 连接Afk服务器
public bool ConnectMySql(bool isSave = false)
{
string connStr = GetConnection2();
string serverName = this.afkSeverId.Text.Trim();//地址
string port = this.afkPortNumber.Text.Trim();//端口
string dbName = this.afkDataBase.Text.Trim();//数据库名
string user = this.afkName.Text.Trim();//用户名
string password = this.afkPassword.Text.Trim();//密码
if (string.IsNullOrWhiteSpace(serverName))
{
MessageUtil.Show("请重新输入Afk数据库地址");
return false;
}
if (string.IsNullOrWhiteSpace(port))
{
MessageUtil.Show("请重新输入Afk数据库端口");
return false;
}
if (string.IsNullOrWhiteSpace(dbName))
{
MessageUtil.Show("请重新输入Afk数据库库名");
return false;
}
if (string.IsNullOrWhiteSpace(user))
{
MessageUtil.Show("请重新输入Afk数据库用户名");
return false;
}
// 测试数据库连接
try
{
if (ConnectingToDatabase2())
{
if (isSave)
{
}
else
{
IniHelper.Write("AFK", "serverName", serverName);
IniHelper.Write("AFK", "port", port);
IniHelper.Write("AFK", "dbName", dbName);
IniHelper.Write("AFK", "user", user);
IniHelper.Write("AFK", "password", password);
RefreshLogUIThread(DateTime.Now + "AFK数据库连接成功.\r\n");
return true;
}
}
else
{
MessageUtil.Show("连接失败,请检查AFK方配置");
return false;
}
}
catch (Exception ex)
{
MessageUtil.Show("连接失败,请检查AFK方配置");
}
return true;
return true;
}
///
/// 说明:创建数据库连接
/// 创建人:龚宇超
/// 创建日期:2017-08-07
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// true if XXXX, false otherwise.
public bool ConnectingToDatabase2()
{
string connStr = GetConnection2();
if (MySqlHelper._connection != null)
{
try
{
MySqlHelper._connection.Close();
MySqlHelper._connection.Dispose();
}
catch (Exception)
{
}
MySqlHelper._connection = null;
}
try
{
MySqlHelper._connection = new MySqlConnection(connStr);
MySqlHelper._connection.Open();
return true;
}
catch (Exception ex)
{
// LogHelper.Instance.WriteLog(ex.Message);
}
return false;
}
///
/// 获取连接服务器的字符串
///
///
public string GetConnection2()
{
return string.Format("Data Source={0};Port={1};Database={2};User ID={3};Password={4};Charset=utf8;Convert Zero Datetime=True;", afkSeverId.Text + "", afkPortNumber.Text + "", afkDataBase.Text + "", afkName.Text + "", afkPassword.Text + "");
}
#endregion
#region 按钮浮动事件
private void OnStartBtn_MouseLeave(object sender, EventArgs e)
{
DevExpress.XtraEditors.SimpleButton btn = (DevExpress.XtraEditors.SimpleButton)sender;
btn.Appearance.BackColor = Color.FromArgb(52, 142, 216);
}
private void OnStartBtn_MouseHover(object sender, EventArgs e)
{
DevExpress.XtraEditors.SimpleButton btn = (DevExpress.XtraEditors.SimpleButton)sender;
btn.Appearance.BackColor = Color.FromArgb(140, 208, 1);
}
private void OnStopBtn_MouseLeave(object sender, EventArgs e)
{
DevExpress.XtraEditors.SimpleButton btn = (DevExpress.XtraEditors.SimpleButton)sender;
btn.Appearance.BackColor = Color.FromArgb(52, 142, 216);
}
private void OnStoptBtn_MouseHover(object sender, EventArgs e)
{
if (this.startBtn.Appearance.BackColor != Color.FromArgb(52, 142, 216))
{
this.startBtn.Appearance.BackColor = Color.FromArgb(52, 142, 216);
}
DevExpress.XtraEditors.SimpleButton btn = (DevExpress.XtraEditors.SimpleButton)sender;
btn.Appearance.BackColor = Color.FromArgb(140, 208, 1);
}
#endregion
#region 初始化数据配置页
private void InitializeDataSettings()
{
if (ConnectServerOther())
{
string explainSql = @"SELECT
A.name AS table_name,
B.name AS column_name,
C.value AS column_description
FROM sys.tables A
INNER JOIN sys.columns B ON B.object_id = A.object_id
LEFT JOIN sys.extended_properties C ON C.major_id = B.object_id AND C.minor_id = B.column_id
WHERE A.name = 'P_synchrTab'";
DataTable explainTab = SqlHelperOther.ExecuteDataTable(explainSql);
DataTable sourceTab = SqlHelperOther.ExecuteDataTable("select * from P_synchrTab");
this.gridView.Columns.Clear();
this.gridControl.DataSource = sourceTab;
foreach (GridColumn gridColumn in this.gridView.Columns)
{
DataRow[] captionRows = explainTab.Select(string.Format("{0}='{1}'", "column_name", gridColumn.FieldName));
if (captionRows.Count() > 0)
{
DataRow captionRow = captionRows[0];
gridColumn.Caption = captionRow["column_description"] + "";
}
if (gridColumn.FieldName.Equals("synchroSql") || gridColumn.FieldName.Equals("targetTabSql") || gridColumn.FieldName.Equals("synLogSql") || gridColumn.FieldName.Equals("afterSql") || gridColumn.FieldName.Equals("relevanceSql") || gridColumn.FieldName.Equals("disableField"))
{
RepositoryItemMemoExEdit reEdit = new RepositoryItemMemoExEdit();
reEdit.ScrollBars = ScrollBars.Vertical;
gridControl.RepositoryItems.Add(reEdit);
gridColumn.ColumnEdit = reEdit;
}
if (gridColumn.FieldName.Equals("directionTag"))
{
DataTable directionTab = new DataTable();
directionTab.Columns.Add("dm");
directionTab.Columns.Add("mc");
directionTab.Rows.Add("0", "同步到朗速");
directionTab.Rows.Add("1", "同步到中航");
directionTab.Rows.Add("10", "不同步");
RepositoryItemLookUpEdit comboxEdit = new RepositoryItemLookUpEdit();
comboxEdit.SearchMode = SearchMode.AutoFilter;
comboxEdit.ShowHeader = false;
comboxEdit.ImmediatePopup = false;
comboxEdit.NullText = "";
comboxEdit.PopupBorderStyle = PopupBorderStyles.Flat;
comboxEdit.AllowNullInput = DefaultBoolean.False;
comboxEdit.DisplayMember = "mc";
comboxEdit.ValueMember = "dm";
//comboxEdit.DataSource = MainImpl.GetDataTableResult(model.SqlSource);
LookUpColumnInfo valueColumn = new LookUpColumnInfo();
valueColumn.Caption = "编码";
valueColumn.FieldName = "dm";
valueColumn.Visible = false;
LookUpColumnInfo textColumn = new LookUpColumnInfo();
textColumn.Caption = "名称";
textColumn.FieldName = "mc";
comboxEdit.Columns.AddRange(new LookUpColumnInfo[] { valueColumn, textColumn });
gridControl.RepositoryItems.Add(comboxEdit);
gridColumn.ColumnEdit = comboxEdit;
comboxEdit.DataSource = directionTab;
}
if (gridColumn.FieldName.Equals("disableTag"))
{
RepositoryItemCheckEdit comboxEdit = new RepositoryItemCheckEdit();
comboxEdit.ValueChecked = "false";
comboxEdit.ValueUnchecked = "true";
gridControl.RepositoryItems.Add(comboxEdit);
gridColumn.ColumnEdit = comboxEdit;
}
if (gridColumn.FieldName.Equals("id") || gridColumn.FieldName.Equals("rightKeyTag"))
{
gridColumn.Visible = false;
}
}
this.gridView.BestFitColumns();
//this.gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
this.gridView.OptionsSelection.MultiSelect = false;
this.gridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseDownFocused;
this.contextMenuStrip.ItemClicked += new ToolStripItemClickedEventHandler(OnContextMenuStrip_ItemClicked);
}
}
#endregion
///
/// 新增按钮
///
///
///
private void addBtn_Click(object sender, EventArgs e)
{
DataTable tab = new DataTable();
tab = (this.gridControl.DataSource as DataTable).Copy();
if (tab.Rows.Count > 0)
{
tab.DefaultView.Sort = "ID ASC";
DataRow lastRow = tab.DefaultView.ToTable().Rows[tab.Rows.Count - 1];
if ((lastRow["id"] + "").Equals("9999999"))
{
if (tab.Rows.Count > 1)
{
DataRow NRow = tab.NewRow();
NRow["id"] = Convert.ToInt32(tab.DefaultView.ToTable().Rows[tab.Rows.Count - 2]["id"] + "") + 1;
tab.Rows.Add(NRow);
}
else
{
DataRow NRow = tab.NewRow();
NRow["id"] = 1;
tab.Rows.Add(NRow);
}
}
else
{
DataRow NRow = tab.NewRow();
NRow["id"] = Convert.ToInt32(tab.DefaultView.ToTable().Rows[tab.Rows.Count - 1]["id"] + "") + 1;
tab.Rows.Add(NRow);
}
this.gridControl.DataSource = tab;
}
}
///
/// 保存按钮
///
///
///
private void savebtn_Click(object sender, EventArgs e)
{
try
{
if (ConnectServerOther())
{
DataTable sourceTab = SqlHelperOther.ExecuteDataTable("select * from P_synchrTab");
DataTable tab = this.gridControl.DataSource as DataTable;
string allSqlStr = string.Empty;
foreach (DataRow row in tab.Rows)
{
if (row.RowState == DataRowState.Added)
{
string addSqlStr = "insert into P_synchrTab ({0}) values ({1});\r\n";
string sqlKey = string.Empty;
string sqlValues = string.Empty;
foreach (DataColumn col in row.Table.Columns)
{
sqlKey += string.Format("{0},", col.ColumnName);
sqlValues += string.Format("'{0}',", (row[col.ColumnName] + "").Replace("'", "''"));
}
allSqlStr += string.Format(addSqlStr, sqlKey.TrimEnd(','), sqlValues.TrimEnd(','));
}
else if (row.RowState == DataRowState.Modified)
{
string updateSqlStr = "update P_synchrTab set {0} = '{1}' where {2} = '{3}';\r\n";
DataRow[] sourceRows = sourceTab.Select(string.Format("id='{0}'", row["id"] + ""));
if (sourceRows.Count() > 0)
{
DataRow sourceRow = sourceRows[0];
foreach (DataColumn col in row.Table.Columns)
{
if (!(row[col.ColumnName] + "").Equals(sourceRow[col.ColumnName] + ""))
{
allSqlStr += string.Format(updateSqlStr, col.ColumnName, (row[col.ColumnName] + "").Replace("'", "''"), "id", row["id"] + "");
}
}
}
}
}
try
{
DialogResult dialogResult = MessageUtil.Show("是否保存当前数据?", MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.OK)
{
if (!string.IsNullOrWhiteSpace(allSqlStr)) SqlHelperOther.ExecuteNonQuery(allSqlStr);
MessageUtil.Show("保存成功");
}
}
catch (Exception ex)
{
MessageUtil.Show(string.Format("保存失败,原因:{0}", ex.Message));
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
///
/// 右键菜单
///
///
///
private void OnContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
try
{
if (ConnectServerOther())
{
DataTable sourceTab = SqlHelperOther.ExecuteDataTable("select * from P_synchrTab");
DataTable dataTab = this.gridControl.DataSource as DataTable;
DataRow row = this.gridView.GetDataRow(this.gridView.FocusedRowHandle);
switch (e.ClickedItem.Name)
{
case "AbutmentNowRow":
string updateSql = "update P_synchrTab set rightKeyTag = '1' where id = {0}";
int updateResult = SqlHelperOther.ExecuteNonQuery(string.Format(updateSql, row["id"] + ""));
break;
case "disableRowData":
string disableSql = "update P_synchrTab set disableTag = 'false' where id = {0}";
int disableResult = SqlHelperOther.ExecuteNonQuery(string.Format(disableSql, row["id"] + ""));
DataRow[] findDisRows = dataTab.Select(string.Format("id='{0}'", row["id"] + ""));
if (findDisRows.Count() > 0)
{
DataRow findDisRow = findDisRows[0];
findDisRow["disableTag"] = "false";
}
break;
case "disablement":
string disablementSql = "update P_synchrTab set disableTag = 'true' where id = {0}";
int disablementResult = SqlHelperOther.ExecuteNonQuery(string.Format(disablementSql, row["id"] + ""));
DataRow[] findUndisRows = dataTab.Select(string.Format("id='{0}'", row["id"] + ""));
if (findUndisRows.Count() > 0)
{
DataRow findUndisRow = findUndisRows[0];
findUndisRow["disableTag"] = "true";
}
break;
case "deleteNowRow":
DialogResult result = MessageUtil.Show("是否确定删除当前选中行?", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
DataRow[] selectRows = sourceTab.Select(string.Format("id='{0}'", row["id"] + ""));
if (selectRows.Count() > 0)
{
string deleteSql = "delete P_synchrTab where id ='{0}'";
SqlHelperOther.ExecuteNonQuery(string.Format(deleteSql, row["id"] + ""));
dataTab.Rows.Remove(row);
MessageUtil.Show("删除成功");
}
else
{
dataTab.Rows.Remove(row);
MessageUtil.Show("删除成功");
}
}
break;
case "Refresh":
this.gridControl.DataSource = SqlHelperOther.ExecuteDataTable("select * from P_synchrTab");
break;
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
///
/// 快捷键
///
///
///
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F1)
{
ConfigurationTool configurationTool = new ConfigurationTool();
configurationTool.Show();
}
}
private void simpleButton1_Click(object sender, EventArgs e)
{
DataRow dr = gridView.GetFocusedDataRow();
ConfigurationTool configurationTool = new ConfigurationTool();
configurationTool.returnContent += new ConfigurationTool.ReturnContent(returnContent);
if (dr != null)
{
configurationTool.SegmentedContent = dr["synchroSql"] + "";
configurationTool.DirectionTag = dr["directionTag"] + "";
}
configurationTool.ShowDialog();
}
private void returnContent(string value)
{
DataRow dr = gridView.GetFocusedDataRow();
dr["synchroSql"] = value;
this.savebtn_Click(null, null);
}
}
}