void AnalyticData(SendMessage data) { int syncCount = 0; bool IsMatch = false; //MachineCodes item = ServerConfiguration.Instance.Details.Where(a => a.UpLoadIdentifer == data.UpLoadIdentifier).FirstOrDefault(); foreach (MachineCodes item in ServerConfiguration.Instance.Details.Where(a => a.UpLoadIdentifer == data.UpLoadIdentifier)) { if (data.UpLoadIdentifier == item.UpLoadIdentifer) { IsMatch = true; // 未设置主键名则跳过 if (string.IsNullOrEmpty(item.PrimarKeys)) { grabPerformer_OutputInfo(string.Format("{0} 提取未执行,原因:未设置主键(PrimaryKeys)参数", item.UpLoadIdentifer)); break; } OracleDapperDber selfDber = new OracleDapperDber(ServerConfiguration.Instance.SelfConnStr); //using (OracleConnection connection = selfDber.CreateConnection() as OracleConnection) //{ if (data.DataColumns != null) { // 在数据中创建表 if (selfDber.Execute(CMCS.CommonADGS.Core.OracleSqlBuilder.BuildHasTableSQL(item.DataTableName)) == 0) { selfDber.Execute(CMCS.CommonADGS.Core.OracleSqlBuilder.BuildTableSQL(item.DataTableName, data.DataColumns)); } } else if (data.DataRows != null) { string execSql = string.Empty; // 生成主键值 string primaryKeyValue = item.UpLoadIdentifer + "-" + CMCS.CommonADGS.Core.OracleSqlBuilder.BuildPrimaryKeyValue(item.PrimarKeys, data.DataRows); if (selfDber.Execute(CMCS.CommonADGS.Core.OracleSqlBuilder.BuildHasRecordSQL(item.DataTableName, primaryKeyValue)) == 0) { execSql = CMCS.CommonADGS.Core.OracleSqlBuilder.BuildInsertSQL(item.DataTableName, primaryKeyValue, item.UpLoadIdentifer, data.DataRows); } else { execSql = CMCS.CommonADGS.Core.OracleSqlBuilder.BuildUpdateSQL(item.DataTableName, primaryKeyValue, item.UpLoadIdentifer, data.DataRows); } syncCount += selfDber.Execute(execSql); } //} } } if (!IsMatch) { grabPerformer_OutputInfo(string.Format("接收到:{0}数据,但未找到对应配置", data.UpLoadIdentifier)); } if (syncCount > 0) { grabPerformer_OutputInfo(string.Format("成功接收:{0}一条数据", data.UpLoadIdentifier)); } }
/// <summary> /// 上传 /// </summary> /// <param name="server"></param> /// <param name="client"></param> /// <param name="tableSynch"></param> /// <returns></returns> private int Upload(OracleDapperDber server, OracleDapperDber client, TableSynch tableSynch) { int synchCount = 0; DataTable dtClient = client.ExecuteDataTable(OracleSqlBuilder.BuildGetNeedSynchTableSQL(tableSynch.TableName, tableSynch.SynchField, this._CommonAppConfig.SyncIdentifier, "上传")); foreach (DataRow dr in dtClient.Rows) { string execSql = string.Empty; if (server.ExecuteDataTable(OracleSqlBuilder.BuildHasRecordSQL(tableSynch.TableName, tableSynch.PrimaryKey, dr[tableSynch.PrimaryKey].ToString())).Rows[0][0].ToString() == "0") { execSql = OracleSqlBuilder.BuildInsertSQL(tableSynch.TableName, tableSynch.SynchField, this._CommonAppConfig.SyncIdentifier, dr); } else { execSql = OracleSqlBuilder.BuildUpdateSQL(tableSynch.TableName, tableSynch.SynchField, this._CommonAppConfig.SyncIdentifier, tableSynch.PrimaryKey, dr); } if (server.Execute(execSql) > 0) { synchCount += 1; client.Execute(OracleSqlBuilder.BuildUpdateSynchFieldSQL(tableSynch.TableName, tableSynch.PrimaryKey, dr[tableSynch.PrimaryKey].ToString(), tableSynch.SynchField, this._CommonAppConfig.SyncIdentifier, "上传")); } } return(synchCount); }
/// <summary> /// 下达 /// </summary> /// <param name="server"></param> /// <param name="client"></param> /// <param name="tableSynch"></param> /// <returns></returns> private int Download(OracleDapperDber server, OracleDapperDber client, TableSynch tableSynch) { int synchCount = 0; DataTable dtServer = server.ExecuteDataTable(OracleSqlBuilder.BuildGetNeedSynchTableSQL(tableSynch.TableName, tableSynch.SynchField)); foreach (DataRow dr in dtServer.Rows) { string execSql = string.Empty; if (client.ExecuteScalar <int>(OracleSqlBuilder.BuildHasRecordSQL(tableSynch.TableName, tableSynch.PrimaryKey, dr[tableSynch.PrimaryKey].ToString())) == 0) { execSql = OracleSqlBuilder.BuildInsertSQL(tableSynch.TableName, tableSynch.SynchField, dr); } else { execSql = OracleSqlBuilder.BuildUpdateSQL(tableSynch.TableName, tableSynch.SynchField, tableSynch.PrimaryKey, dr); } if (client.Execute(execSql) > 0) { synchCount += 1; server.Execute(OracleSqlBuilder.BuildUpdateSynchFieldSQL(tableSynch.TableName, tableSynch.PrimaryKey, dr[tableSynch.PrimaryKey].ToString(), tableSynch.SynchField)); } } return(synchCount); }
/// <summary> /// 上报数据 /// </summary> /// <param name="entity"></param> /// <param name="thirdDber"></param> /// <param name="output"></param> private void UpLoadData(TableOrView entity, OracleDapperDber thirdDber, Action <string, eOutputType> output) { //查询本地是否有待上报数据 string sbSearch = "select "; foreach (var item in entity.PropertySetDetails) { sbSearch += string.Format("{0},", item.Source); } sbSearch = sbSearch.Trim(','); sbSearch += string.Format(" from {0} ", entity.Source); if (!string.IsNullOrWhiteSpace(entity.TimeIntervalProperty)) { int intervalValue = 7; string configValue = commonDAO.GetAppletConfigString("数据同步智仁接口", "数据上报时间间隔(天)"); if (!string.IsNullOrWhiteSpace(configValue)) { Int32.TryParse(configValue, out intervalValue); } DateTime startTime = DateTime.Now.AddDays(-intervalValue); sbSearch += string.Format(" where {0}>=to_date('{1}','yyyy-MM-dd hh24:mi:ss')", entity.TimeIntervalProperty, startTime); } DataTable dt = SelfDber.ExecuteDataTable(sbSearch); if (dt == null || dt.Rows.Count <= 0) { return; } Boolean ishavepk = entity.PropertySetDetails.Count(a => a.DesPrimaryKey != null && a.DesPrimaryKey.ToLower() == "true") > 0; foreach (DataRow item in dt.Rows) { //只有更新和新增操作 string strChaXun = string.Format("select * from {0} where 1=1 ", entity.Destination); if (ishavepk) { foreach (var pk in entity.PropertySetDetails.Where(a => a.DesPrimaryKey != null && a.DesPrimaryKey.ToLower() == "true")) { if (!string.IsNullOrWhiteSpace(pk.DesType) && pk.DesType.ToLower() == "datetime") { pk.Format = "yyyy-MM-dd hh24:mi:ss"; strChaXun += string.Format("and {0}=to_date('{1}','{2}') ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString(), pk.Format); } else { strChaXun += string.Format("and {0}='{1}' ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString()); } } } else { foreach (var pk in entity.PropertySetDetails) { if (!string.IsNullOrWhiteSpace(pk.DesType) && pk.DesType.ToLower() == "datetime") { pk.Format = "yyyy-MM-dd hh24:mi:ss"; strChaXun += string.Format("and {0}=to_date('{1}','{2}') ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString(), pk.Format); } else { strChaXun += string.Format("and {0}='{1}' ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString()); } } } DataTable dtHaveData = thirdDber.ExecuteDataTable(strChaXun); if (dtHaveData == null || dtHaveData.Rows.Count <= 0) { //新增 string insertSql = string.Format(@"insert into {0} (", entity.Destination); string names = ""; string values = ""; foreach (var detail in entity.PropertySetDetails) { names += string.Format("{0},", detail.Destination); if (detail.DesType != null && detail.DesType.ToLower() == "datetime" && !string.IsNullOrWhiteSpace(detail.Format)) { values += string.Format("{0},", item[detail.Source] == DBNull.Value ? "''" : ("'" + DateTime.Parse(item[detail.Source].ToString()).ToString(detail.Format) + "'")); } else { values += string.Format("'{0}',", item[detail.Source] == DBNull.Value ? "" : item[detail.Source].ToString()); } } insertSql += names.Trim(',') + ") values (" + values.Trim(',') + ")"; if (thirdDber.Execute(insertSql) > 0) { output(string.Format("接口上报数据【{0}】已同步,操作:新增", entity.Description), eOutputType.Normal); } } else { //更新 string updateSql = string.Format("update {0} set ", entity.Destination); foreach (var detail in entity.PropertySetDetails) { if (detail.DesType != null && detail.DesType.ToLower() == "datetime" && !string.IsNullOrWhiteSpace(detail.Format)) { updateSql += string.Format("{0}={1},", detail.Destination, item[detail.Source] == DBNull.Value ? "''" : ("'" + DateTime.Parse(item[detail.Source].ToString()).ToString(detail.Format) + "'")); } else { updateSql += string.Format("{0}='{1}',", detail.Destination, item[detail.Source] == DBNull.Value ? "" : item[detail.Source].ToString()); } } //if (entity.Description == "编码接口表") // updateSql = updateSql.Trim(',') + string.Format(" where id='{0}'", dtHaveData.Rows[0]["TRUCKENTERID"].ToString()); //else updateSql = updateSql.Trim(','); string updateWhere = ""; if (ishavepk) { int index = 0; foreach (var pk in entity.PropertySetDetails.Where(a => a.DesPrimaryKey != null && a.DesPrimaryKey.ToLower() == "true")) { if (!string.IsNullOrWhiteSpace(pk.DesType) && pk.DesType.ToLower() == "datetime") { pk.Format = "yyyy-MM-dd hh24:mi:ss"; updateWhere += string.Format("{3} {0}=to_date('{1}','{2}') ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString(), pk.Format, (index == 0 ? "" : "and")); } else { updateWhere += string.Format("{2} {0}='{1}' ", pk.Destination, item[pk.Source] == DBNull.Value ? "" : item[pk.Source].ToString(), (index == 0 ? "" : "and")); } index++; } if (!string.IsNullOrWhiteSpace(updateWhere)) { updateWhere = " where " + updateWhere; } } if (string.IsNullOrWhiteSpace(updateWhere)) { updateWhere = string.Format(" where {0}='{1}'", entity.PropertySetDetails.First().Destination, dtHaveData.Rows[0][entity.PropertySetDetails.First().Destination].ToString()); } updateSql = updateSql + " " + updateWhere; //updateSql = updateSql.Trim(',') + string.Format(" where {0}='{1}'", entity.PropertySetDetails.First().Destination, dtHaveData.Rows[0][entity.PropertySetDetails.First().Destination].ToString()); if (thirdDber.Execute(updateSql) > 0) { output(string.Format("接口取数【{0}】已同步,操作:更新", entity.Description), eOutputType.Normal); } } } }
/// <summary> /// 同步数据 /// </summary> private void Synch() { if (!TestPing(this._CommonAppConfig.ServerIp)) { OutputInfoMethod(string.Format("服务器网络已断开"), eOutputType.Error); return; } OracleDapperDber serverDber = new OracleDapperDber(this._CommonAppConfig.ServerConnStr); OracleDapperDber clientDber = new OracleDapperDber(this._CommonAppConfig.ClientConnStr); if (string.IsNullOrEmpty(this._CommonAppConfig.SyncIdentifier)) { OutputInfoMethod(string.Format("同步标识未设置"), eOutputType.Error); return; } foreach (TableSynch tableSynch in this._CommonAppConfig.TableSynchs) { try { if (!tableSynch.Enabled) { continue; } // 未设置表名则跳过 if (string.IsNullOrEmpty(tableSynch.TableName.Trim())) { OutputInfoMethod(string.Format("【{0}】 同步未执行,原因:未设置表名(TableName)参数", tableSynch.SynchTitle), eOutputType.Error); continue; } // 未设置主键名则跳过 if (string.IsNullOrEmpty(tableSynch.PrimaryKey.Trim())) { OutputInfoMethod(string.Format("【{0}】 同步未执行,原因:未设置主键(PrimaryKey)参数", tableSynch.TableName), eOutputType.Error); continue; } // 未设置同步标识则跳过 if (string.IsNullOrEmpty(tableSynch.SynchField.Trim())) { OutputInfoMethod(string.Format("【{0}】 同步未执行,原因:未设置同步标识字段(SynchField)参数", tableSynch.TableName), eOutputType.Error); continue; } //判断两个库表是否存在 if (serverDber.Execute(OracleSqlBuilder.BuildHasTableSQL(tableSynch.TableName)) == 0) { OutputInfoMethod(string.Format("【{0}】 同步未执行,原因:服务器端不存在此表{1}", tableSynch.SynchTitle, tableSynch.TableName), eOutputType.Error); continue; } if (clientDber.Execute(OracleSqlBuilder.BuildHasTableSQL(tableSynch.TableName)) == 0) { OutputInfoMethod(string.Format("【{0}】 同步未执行,原因:就地端不存在此表{1}", tableSynch.SynchTitle, tableSynch.TableName), eOutputType.Error); continue; } //判断两个库表字段是否一致 DataTable dt1 = serverDber.ExecuteDataTable(OracleSqlBuilder.BuildGetNullTableSQL(tableSynch.TableName)); DataTable dt2 = clientDber.ExecuteDataTable(OracleSqlBuilder.BuildGetNullTableSQL(tableSynch.TableName)); if (!OracleSqlBuilder.CompareTableField(dt1, dt2)) { OutputInfoMethod(string.Format("【{0}】两端表{1}列名不一致", tableSynch.SynchTitle, tableSynch.TableName), eOutputType.Important); IList <DataColumn> columns = OracleSqlBuilder.CompareTableFieldAndReturn(dt1, dt2); if (columns != null && columns.Count > 0) { clientDber.Execute(OracleSqlBuilder.BuildAddColumnSQL(columns, serverDber)); clientDber.Execute(OracleSqlBuilder.BuildColumnDefaultSQL(columns, serverDber)); OutputInfoMethod(string.Format("【{0}】列已同步", tableSynch.SynchTitle, tableSynch.TableName), eOutputType.Important); } } int res = 0; switch (tableSynch.SynchType) { case "上传": res = Upload(serverDber, clientDber, tableSynch); OutputInfoMethod(string.Format("【{0}】 本次上传 {1} 条", tableSynch.SynchTitle, res), eOutputType.Normal); break; case "下达": res = Download(serverDber, clientDber, tableSynch); OutputInfoMethod(string.Format("【{0}】 本次下达 {1} 条", tableSynch.SynchTitle, res), eOutputType.Normal); break; case "双向": //先下达 再上传 res = Download(serverDber, clientDber, tableSynch); OutputInfoMethod(string.Format("【{0}】 本次下达 {1} 条", tableSynch.SynchTitle, res), eOutputType.Normal); res = Upload(serverDber, clientDber, tableSynch); OutputInfoMethod(string.Format("【{0}】 本次上传 {1} 条", tableSynch.SynchTitle, res), eOutputType.Normal); break; } } catch (Exception ex) { OutputErrorMethod(string.Format("【{0}】 {1}同步失败", tableSynch.SynchTitle, tableSynch.SynchType), ex); } } //删除数据 foreach (CmcsWaitForHandleEvent item in clientDber.Entities <CmcsWaitForHandleEvent>("where DataFlag=0 and EventCode like '%删除%'")) { bool isSuccess = false; eEventCode eventCode; bool a = Enum.TryParse <eEventCode>(item.EventCode, out eventCode); if (!Enum.TryParse <eEventCode>(item.EventCode, out eventCode)) { continue; } switch (eventCode) { case eEventCode.汽车智能化_删除未完成运输记录: isSuccess = clientDber.DeleteBySQL <CmcsUnFinishTransport>("where TransportId=:TransportId", new { TransportId = item.ObjectId }) > 0; if (isSuccess) { OutputInfoMethod(string.Format("事件:{0} ObjectId:{1}", eEventCode.汽车智能化_删除未完成运输记录.ToString(), item.ObjectId), eOutputType.Normal); } break; case eEventCode.汽车智能化_删除入厂煤运输记录: isSuccess = clientDber.DeleteBySQL <CmcsBuyFuelTransport>("where Id=:Id", new { Id = item.ObjectId }) > 0; if (isSuccess) { OutputInfoMethod(string.Format("事件:{0} ObjectId:{1}", eEventCode.汽车智能化_删除入厂煤运输记录.ToString(), item.ObjectId), eOutputType.Normal); } break; case eEventCode.汽车智能化_删除出厂煤运输记录: isSuccess = clientDber.DeleteBySQL <CmcsSaleFuelTransport>("where Id=:Id", new { Id = item.ObjectId }) > 0; if (isSuccess) { OutputInfoMethod(string.Format("事件:{0} ObjectId:{1}", eEventCode.汽车智能化_删除出厂煤运输记录.ToString(), item.ObjectId), eOutputType.Normal); } break; default: break; } if (isSuccess) { item.DataFlag = 1; clientDber.Update(item); } } }