/// <summary> /// 导出文件附件 /// </summary> /// <param name="wherestr">搜索条件</param> /// <returns>附件信息</returns> public ActionResult ExportFile(string name = "", string typeId = "", string dbId = "", int self = 0) { try { string filename = HttpUtility.UrlEncode(string.Format("导出报表_脚本任务_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")), Encoding.UTF8); string path = System.Web.HttpContext.Current.Server.MapPath("~/tmp/"); string where = "1=1"; List <object> param = new List <object>(); #region 添加参数 if (string.IsNullOrWhiteSpace(name) == false) { where += " AND NAME LIKE '%" + name.Replace('\'', ' ') + "%'"; } if (string.IsNullOrWhiteSpace(typeId) == false) { where += " AND TYPE_ID = ?"; param.Add(typeId); } if (string.IsNullOrWhiteSpace(dbId) == false) { where += " AND DB_ID = ?"; param.Add(dbId); } #endregion int count = 0; var dt = BF_ST_NODE.Instance.GetDataTable(0, 0, ref count, name, typeId, dbId, self); if (dt == null) { return(ShowAlert("导出数据到Excel出现错误:未查询出数据")); } dt.Columns.Remove("ID"); dt.Columns.Remove("LAST_TASK_ID"); dt.Columns["NAME"].Caption = "任务名称"; dt.Columns["TYPENAME"].Caption = "类型"; dt.Columns["TASKNAME"].Caption = "最新任务"; dt.Columns["DBNAME"].Caption = "数据库名称"; dt.Columns["RUN_STATUS"].Caption = "运行状态"; dt.Columns["LAST_TASK_IS"].Caption = "是否成功"; dt.Columns["LAST_TASK_ST"].Caption = "开始时间"; dt.Columns["LAST_TASK_FT"].Caption = "结束时间"; dt.Columns["CREATE_NAME"].Caption = "创建者"; dt.Columns["CREATE_TIME"].Caption = "创建时间"; dt.Columns["UPDATE_TIME"].Caption = "更新时间"; dt.Columns["UPDATE_NAME"].Caption = "更新者"; Library.Export.ExcelFile export = new Library.Export.ExcelFile(path); string fullName = export.ToExcel(dt); if (string.IsNullOrWhiteSpace(fullName) == true) { return(ShowAlert("未生成Excel文件")); } System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Clear();//清除缓冲区所有内容 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); System.Web.HttpContext.Current.Response.WriteFile(fullName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); //删除文件 export.Delete(fullName); } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "导出默认报表[DB]到Excel出错:" + ex.ToString()); return(ShowAlert("导出数据到Excel出现未知错误:" + ex.Message)); } return(ShowAlert("导出成功")); }
/// <summary> /// 备份 /// </summary> /// <returns></returns> public ActionResult Backups() { string path = System.Web.HttpContext.Current.Server.MapPath("~/tmp/"); string fileName = string.Format("口径脚本备份_{0}.sql", DateTime.Now.ToString("yyyyMMddHHmmss")); try { if (System.IO.Directory.Exists(path) == false) { System.IO.Directory.CreateDirectory(path); } DataTable dt = BF_ST_NODE.Instance.GetTableFields("ID, NAME, DB_ID, CONTENT"); if (dt == null || dt.Rows.Count < 1) { return(ShowAlert("没有脚本")); } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path + fileName, false, Encoding.UTF8)) { sw.WriteLine("/// #####################################################################"); sw.WriteLine(string.Format("/// {0} 的口径脚本备份", BF_SYS_CONFIG.SystemName)); sw.WriteLine(string.Format("/// 本文件于 {0} 由 {1} 备份生成", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), SystemSession.UserName)); sw.WriteLine(string.Format("/// 本文件共包含 {0} 个脚本,以下为脚本内容:", dt.Rows.Count)); sw.WriteLine("/// #####################################################################"); sw.WriteLine(); sw.WriteLine(); foreach (DataRow dr in dt.Rows) { int id = Convert.ToInt32(dr["ID"]); sw.WriteLine(string.Format("/// {0} 开始 >>>>> ************************************************************ >>>>>", id)); sw.WriteLine("/// ID:" + Convert.ToInt32(dr["ID"])); sw.WriteLine("/// NAME:" + Convert.ToString(dr["NAME"])); sw.WriteLine("/// DB_ID:" + Convert.ToInt32(dr["DB_ID"])); sw.WriteLine("/// 以下是脚本内容"); sw.WriteLine(Convert.ToString(dr["CONTENT"])); sw.WriteLine(string.Format("/// {0} 结束 <<<<< ************************************************************ <<<<<", id)); sw.WriteLine(); sw.WriteLine(); } } System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Clear();//清除缓冲区所有内容 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); System.Web.HttpContext.Current.Response.WriteFile(path + fileName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "备份脚本代码到文件出错:" + ex.ToString()); return(ShowAlert("备份脚本代码到文件出错:" + ex.Message)); } finally { if (System.IO.File.Exists(path + fileName)) { try { System.IO.File.Delete(path + fileName); } catch (Exception e) { } } } return(null); }
public CronTest(int id, string expression) : base(id, expression) { BLog.Write(BLog.LogLevel.INFO, string.Format("任务【{0}】已经初始化。", id)); }
// 加入错题集:如果是批注状态,批注的图片入错题集,否则原始图片入错题集 private void btnJoinErrCol_Click(object sender, EventArgs e) { if (cbSubject.SelectedIndex == 0) { MessageBox.Show("请选择科目."); return; } if (!isDraw) { gpEra = plCamera.CreateGraphics(); gpEra.SmoothingMode = SmoothingMode.AntiAlias; gpEra.InterpolationMode = InterpolationMode.HighQualityBicubic; gpEra.CompositingQuality = CompositingQuality.HighQuality; ImageFromControl(ref gpEra, ref imgEra); Progress.Add(new Bitmap(imgEra)); } if (commentImageList1.Count < config.MaxCommentImageCount) { BLog.ToDB("加入错题集"); btnJoinErrCol.Enabled = false; string dirName = config.ErrColSavePath + "\\" + cbSubject.Items[cbSubject.SelectedIndex].ToString() + "\\" + DateTime.Now.ToString("yyyyMMdd"); if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName); string imgPath = dirName + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".PNG"; if (img == null) { ImageFromControl(ref gpHide); } if (isPen) { img.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png); } else { Graphics g = plCamera.CreateGraphics(); ImageFromControl(ref g); img.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png); } commentImageList1.AddPic(imgPath); List<Bitmap> temp1 = new List<Bitmap>(); foreach (Bitmap img2 in Progress) temp1.Add(img2); Stack<Bitmap> temp2 = new Stack<Bitmap>(); foreach (Bitmap img2 in Backup) temp2.Push(img2); lmgList.Add(temp1); lmgStack.Add(temp2); NoticeShow("已加入错题集"); Thread.Sleep(1000); btnJoinErrCol.Enabled = true; img = null; } else { MessageBox.Show(string.Format("浏览历史列表只能保存{0}个批注,请清空后再保存", config.MaxCommentImageCount)); } }
/// <summary> /// 获取下拉树的选项列表 /// </summary> /// <param name="entity">实体</param> /// <returns></returns> public static DataTable GetSelectTreaOptions(Entity entity) { DataTable options = new DataTable(); if (entity == null || entity.FORM_QUERY_TYPE != (short)Enums.FormQueryType.拉树选择 || string.IsNullOrWhiteSpace(entity.SELECT_DETAIL)) { return(options); } string[] selectDetail = entity.SELECT_DETAIL.Split(new char[] { ':' }); if (selectDetail.Length < 2) { return(options); } if (selectDetail[0] == Enums.FormSelectType.枚举值.GetHashCode().ToString()) { options.Columns.Add("k"); options.Columns.Add("v"); options.Columns.Add("p"); string[] ops = selectDetail[1].Split(new char[] { '\r', '\n', ';', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string op in ops) { string[] os = op.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); if (os.Length < 3) { continue; } DataRow row = options.NewRow(); row["v"] = (string.IsNullOrWhiteSpace(os[0]) ? "" : BF_FORM.Instance.GetReadParam(os[0]));; row["k"] = (string.IsNullOrWhiteSpace(os[1]) ? "" : BF_FORM.Instance.GetReadParam(os[1])); row["p"] = (string.IsNullOrWhiteSpace(os[2]) ? "0" : BF_FORM.Instance.GetReadParam(os[2])); options.Rows.Add(row); } } else if (selectDetail[0] == Enums.FormSelectType.表查询.GetHashCode().ToString()) { string[] infos = selectDetail[1].Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); if (infos.Length < 5) { return(options); } int dbid = 0; if (int.TryParse(infos[0], out dbid) == false) { return(options); } string where = "1=1"; if (infos.Length > 5 && string.IsNullOrWhiteSpace(infos[5]) == false) { where = infos[5]; } try { int rowsCount = -1; string sql = string.Format("SELECT {0} v,{1} k,{2} p FROM {3} WHERE {4}", infos[2], infos[3], infos[4], infos[1], where); sql = BF_FORM.Instance.GetReadParam(sql); options = BF_DATABASE.Instance.ExecuteSelectSQL(dbid, sql, null, ref rowsCount, 0); } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "加载报表" + entity.REPORT_ID + ",筛选字段" + entity.FIELD_NAME + "的下拉筛选项出错:" + ex.ToString()); } } else if (selectDetail[0] == Enums.FormSelectType.SQL语句.GetHashCode().ToString()) { string[] infos = selectDetail[1].Split('◎'); if (infos.Length < 2) { return(options); } int dbid = 0; if (int.TryParse(infos[0], out dbid) == false) { return(options); } string sql = infos[1];//得到SQL语句 if (string.IsNullOrWhiteSpace(sql) == false) { int rowsCount = -1; sql = BF_FORM.Instance.GetReadParam(sql); options = BF_DATABASE.Instance.ExecuteSelectSQL(dbid, sql, null, ref rowsCount, 0); } } return(options); }
public JsonResult Edit(SR_TOPIC_FUNDS.Entity ent, FormCollection collection) { JsonResultData result = new JsonResultData(); try { //throw new Exception("抛出错误"); #region 00.数据校验(暂未实现) //校验经费总金额与清单经费金额之和是否相等 #endregion int fundsId = ent.ID; #region 01.保存经费总表 ent.UPDATE_TIME = DateTime.Now; ent.UPDATE_UID = SystemSession.UserID; if (ent.ID == 0) { fundsId = SR_TOPIC_FUNDS.Instance.GetNextValueFromSeqDef(); ent.CREATE_TIME = DateTime.Now; ent.CREATE_UID = SystemSession.UserID; ent.ID = fundsId; SR_TOPIC_FUNDS.Instance.Add(ent); } else { SR_TOPIC_FUNDS.Instance.UpdateByKey(ent, ent.ID); } #endregion #region 01-2.附件银行卡信息自动存储 short isDefault = Convert.ToInt16(collection["IS_DEFAULT_BANK"]); var bankList = SR_BANK.Instance.GetList <SR_BANK.Entity>("CREATE_UID=?", SystemSession.UserID); if (bankList != null && bankList.Count > 0) { var bank = bankList.FirstOrDefault(p => p.BANK_NO == ent.BANK_NO); if (bank != null && bank.ID > 0) { bank.BANK_NAME = ent.BANK_NAME; bank.BANK_ADDRESS = ent.BANK_ADDRESS; bank.USER_NAME = ent.USER_NAME; bank.USER_PHONE = ent.USER_PHONE; bank.IS_DEFAULT = isDefault; if (isDefault == 1) { foreach (var item in bankList) { item.IS_DEFAULT = 0; SR_BANK.Instance.UpdateByKey(item, item.ID); } } SR_BANK.Instance.UpdateByKey(bank, bank.ID); } else { if (isDefault == 1) { foreach (var item in bankList) { item.IS_DEFAULT = 0; SR_BANK.Instance.UpdateByKey(item, item.ID); } } SaveBank(ent, isDefault); } } else { SaveBank(ent, isDefault); } #endregion int addCount = 0, updateCount = 0, delCount = 0; #region 02.保存经费清单列表 var fundsDetails = collection["FundsDetails"]; if (!string.IsNullOrWhiteSpace(fundsDetails) && fundsDetails.Length > 0) { SR_TOPIC_FUNDS_DETAIL.Instance.SaveFundsDetail(fundsId, ent.TOPIC_ID, fundsDetails, out addCount, out updateCount, out delCount); #region 修改经费清单表字段:TOPIC_ID、TOPIC_FUNDS_ID using (BDBHelper db = new BDBHelper()) { db.ExecuteNonQuery(string.Format(@"UPDATE SR_TOPIC_FUNDS_DETAIL SET TOPIC_ID={0} WHERE TOPIC_FUNDS_ID={1}", ent.TOPIC_ID, fundsId)); } #endregion } #endregion result.IsSuccess = true; result.Message = string.Format(@"填报经费报销信息成功:新增【{0}】,修改【{1}】,删除【{2}】", addCount, updateCount, delCount); } catch (Exception ex) { string err = string.Format(@"填报经费报销信息失败:{0}", ex.Message); result.IsSuccess = false; result.Message = err; BLog.Write(BLog.LogLevel.ERROR, err); WriteOperationLog(BLog.LogLevel.ERROR, false, Modular, "经费报销填报", "", err); } return(Json(result, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 表单模板(如果选择了修改和删除必须要传rowKey) /// </summary> /// <param name="formId">表单ID</param> /// <param name="op">功能选择(0:添加;1:修改;2:删除)</param> /// <param name="rowKey">主键值</param> /// <returns></returns>fromId public ActionResult Template(int formId = 0, int op = 0, string rowKey = "", string yyyy = "", string yyyymm = "", string yyyymmdd = "") { #region 验证数据参数 if (formId <= 0 || op >= 2) { ViewBag.Message = "对不起!表单没有找到formId或op参数,请联系管理员。"; // ShowAlert(ViewBag.Message);//跳转至错误页 return(View()); } if (op != 0) { if (rowKey == null || rowKey.Trim() == "") { ViewBag.Message = "对不起!表单没有找rowKey参数值,请联系管理员。"; return(View()); } rowKey = rowKey.Trim(); } #endregion #region 查询基本信息 BF_FORM.Entity entity = BF_FORM.Instance.GetEntityByKey <BF_FORM.Entity>(formId); string tableName = entity.TABLE_NAME;//表名 List <BF_FORM.FieldInfo> FieldList = JsonConvert.DeserializeObject <List <BF_FORM.FieldInfo> >(entity.FIELDS); if (FieldList.Count <= 0) { ViewBag.Message = "对不起!表对应的字段有误,请联系管理员。"; return(View()); } DataRow dataRow = null; #region 查询要编辑的数据 if (op == 1) { string strMessage = ""; entity.TABLE_NAME = BF_FORM.Instance.GetTableName(entity, yyyy, yyyymm, yyyymmdd, ref strMessage);//得到动态表名 if (string.IsNullOrEmpty(strMessage) == false || string.IsNullOrEmpty(entity.TABLE_NAME)) { BLog.Write(BLog.LogLevel.WARN, strMessage); ViewBag.Message = strMessage; // ShowAlert(strMessage);//跳转至错误页 return(View()); } DataTable data = BF_FORM.Instance.GetData(entity.DB_ID, entity.TABLE_NAME, "*", FieldList, rowKey); if (data != null && data.Rows.Count > 0) { dataRow = data.Rows[0]; } } #endregion #endregion string strHtml = BF_FORM.Instance.GenerateTemplate(op, FieldList, dataRow);//生成模板 if (string.IsNullOrEmpty(strHtml)) { ViewBag.Message = "模板生成出现异常!请联系管理"; return(View()); } ViewBag.js_Code = (string.IsNullOrWhiteSpace(entity.JS_CODE) ? "" : "<div class=\"layui-form-item\">" + entity.JS_CODE + "</div>"); ViewBag.formHtml = strHtml;//生成的表单 return(View()); }
/// <summary> /// 到达时间点之后,执行具体任务(本方法由基类自动调用,不需要在外部来调用) /// </summary> /// <param name="runTime">当前时间点</param> /// <returns></returns> protected override bool Execute(DateTime runTime) { if (Main.IsRun == false) { WriteLog(0, BLog.LogLevel.INFO, string.Format("服务已经停止,脚本流【{0}】将不会执行任务。", ID)); return(false); } //WriteLog(0, BLog.LogLevel.DEBUG, string.Format("脚本流【{0}】即将获取执行中的实例,如果有实例处于运行中,将不会创建新实例。", ID)); var scr = BLL.EM_SCRIPT.Instance.GetScriptSupervene(ID); //WriteLog(0, BLog.LogLevel.DEBUG, string.Format("获取是否为并行任务。")); if (scr != null && scr.ID > 0) { WriteLog(0, BLog.LogLevel.DEBUG, string.Format("获取当前任务组【" + ID + "】为并行任务。")); try { var ipNotLists = global.OpIpNotList("getall"); BLog.Write(BLog.LogLevel.INFO, "1输出未在线的ip:" + string.Join(",", ipNotLists.Select(p => p.V))); int effectCount = global.GetEffectMonitKVCount(); List <KV> kvs = global.OpMonitKVList("getall"); WriteLog(0, BLog.LogLevel.INFO, string.Format("输出内存在写入的拷贝文件数:" + kvs.Count)); WriteLog(0, BLog.LogLevel.INFO, string.Format("输出有效的待拷贝文件数:" + effectCount)); if (effectCount > 0) { } else { WriteLog(0, BLog.LogLevel.INFO, string.Format("并行任务【自动上传文件】无待上传文件,将不创建任务组实例")); return(false); } #region 判断监控文件表中是否有待处理的monit_file. 没有将跳出任务组实例的创建--作废 // //string sql = string.Format(@"select count(1) from FM_MONIT_FILE where COPY_STATUS=0 or COPY_STATUS=3"); // #region 再次验证和清理未在线终端 // //var ipArr = global.ipList.ToArray(); // //for (int i = 0; i < ipArr.Count(); i++) // //{ // // if (Request.PingIP(ipArr[i].Value) && global.ipList.ContainsKey(ipArr[i].Key)) // // { // // global.ipList.Remove(ipArr[i].Key);//移除已在线的终端 // // } // //} // var ipNotLists = global.OpIpNotList("getall"); // if (ipNotLists != null && ipNotLists.Count > 0) // { // int cnt = ipNotLists.Count; // for (int i = cnt - 1; i >= 0; i--) // { // var item = ipNotLists[i]; // if (Librarys.ApiRequest.Request.PingIP(item.V)) // { // global.OpIpNotList("remove", item); // } // } // ipNotLists = global.OpIpNotList("getall"); // } // #endregion // string sql = string.Format(@" SELECT ID, COMPUTER_ID // FROM (SELECT A.ID, A.COMPUTER_ID, ROW_NUMBER () OVER (ORDER BY A.ID) RN // FROM FM_MONIT_FILE A // LEFT JOIN // ( SELECT DISTINCT REGEXP_SUBSTR ('{0}', // '[^,]+', // 1, // LEVEL) // AS COMPUTER_ID // FROM DUAL // CONNECT BY REGEXP_SUBSTR ('{0}', // '[^,]+', // 1, // LEVEL) // IS NOT NULL) C // ON (A.COMPUTER_ID = C.COMPUTER_ID) // LEFT JOIN FM_FILE_FORMAT F ON (F.ID=A.FILE_FORMAT_ID) // WHERE NVL (C.COMPUTER_ID, 0) = 0 AND F.NAME<>'Folder' // AND (A.COPY_STATUS = 0 OR A.COPY_STATUS = 3)) //WHERE RN <={1}", string.Join(",", ipNotLists.Select(p => p.K).Distinct()), Main.EachSearchUploadCount); // //string sql = string.Format(@" SELECT A.ID,A.COMPUTER_ID // // FROM FM_MONIT_FILE A // // LEFT JOIN FM_file_FORMAT F ON A.FILE_FORMAT_ID=F.ID // // WHERE (A.COPY_STATUS = 0 OR A.COPY_STATUS = 3) and F.NAME<>'Folder' // // AND ( ({0} = 0) OR ({0} > 0 AND A.COMPUTER_ID NOT IN ({1}))) // // AND ROWNUM <= {2} // // ORDER BY A.ID", ipNotLists.Count, // // ipNotLists.Count == 0 ? "0" : string.Join(",", ipNotLists.Select(p => p.K).Distinct()), Main.EachSearchUploadCount); // DataTable dt = null; // using (BDBHelper dbop = new BDBHelper()) // { // dt = dbop.ExecuteDataTable(sql); // } // if (dt != null && dt.Rows.Count > 0) // { } // else // { // WriteLog(0, BLog.LogLevel.INFO, string.Format("并行任务【自动上传文件】无待上传文件,将不创建任务组实例", string.Format("执行的sql语句为:{0}", sql), ID)); // return false; // } #endregion } catch (Exception ex) { WriteLog(0, BLog.LogLevel.INFO, string.Format("监控错误:{0}", ex.Message)); return(false); } lock (this) { int curNum = 0; WriteLog(0, BLog.LogLevel.DEBUG, string.Format("在创建脚本流实例前的判断:curNum{0},MaxUploadCount{1},已CurUploadCount{2}。", curNum, Main.MaxUploadCount.ToString(), Main.CurUploadCount)); while (curNum < Main.MaxUploadCount && Main.CurUploadCount < Main.MaxUploadCount) { WriteLog(0, BLog.LogLevel.DEBUG, string.Format("curNum{0},MaxUploadCount{1},已有的上传CurUploadCount{2}。", curNum, Main.MaxUploadCount.ToString(), Main.CurUploadCount)); long scriptCaseID = 0; try { //先尝试取之前未完成的节点(排除并发任务组)+执行中的任务实例 //BLL.EM_SCRIPT_CASE.Entity scriptCaseEntity = BLL.EM_SCRIPT_CASE.Instance.GetRunningCase(ID); //if (scriptCaseEntity != null) //{ // WriteLog(scriptCaseEntity.ID, BLog.LogLevel.DEBUG, string.Format("脚本流【{0}】找到了之前未运行完成的实例【{1}】,本次任务将不会创建新实例。", ID, scriptCaseEntity.ID)); // return false; //} //else //{ ErrorInfo err = new ErrorInfo(); if (CreateScriptCase(ID, ref scriptCaseID, ref err) == true) { WriteLog(scriptCaseID, BLog.LogLevel.INFO, string.Format("脚本流【{0}】成功创建了新的实例【{1}】,等待执行。", ID, scriptCaseID)); Main.CurUploadCount++; } else { WriteLog(scriptCaseID, BLog.LogLevel.WARN, err.Message); //标记为失败状态 if (scriptCaseID > 0) { BLL.EM_SCRIPT_CASE.Instance.SetFail(scriptCaseID); } return(false); } //} //_dicTaskers.Add(ID, null); } catch (Exception ex) { WriteLog(scriptCaseID, BLog.LogLevel.WARN, "创建脚本流实例发生了未知错误。" + ex.ToString()); //标记为失败状态 if (scriptCaseID > 0) { BLL.EM_SCRIPT_CASE.Instance.SetFail(scriptCaseID); } return(false); } curNum++; } } } else { #region long scriptCaseID = 0; try { //先尝试取之前未完成的节点(排除并发任务组)+执行中的任务实例 BLL.EM_SCRIPT_CASE.Entity scriptCaseEntity = BLL.EM_SCRIPT_CASE.Instance.GetRunningCase(ID); if (scriptCaseEntity != null) { WriteLog(scriptCaseEntity.ID, BLog.LogLevel.DEBUG, string.Format("脚本流【{0}】找到了之前未运行完成的实例【{1}】,本次任务将不会创建新实例。", ID, scriptCaseEntity.ID)); return(false); } else { ErrorInfo err = new ErrorInfo(); if (CreateScriptCase(ID, ref scriptCaseID, ref err, false) == true) { WriteLog(scriptCaseID, BLog.LogLevel.INFO, string.Format("脚本流【{0}】成功创建了新的实例【{1}】,等待执行。", ID, scriptCaseID)); } else { WriteLog(scriptCaseID, BLog.LogLevel.WARN, err.Message); //标记为失败状态 if (scriptCaseID > 0) { BLL.EM_SCRIPT_CASE.Instance.SetFail(scriptCaseID); } return(false); } } } catch (Exception ex) { WriteLog(scriptCaseID, BLog.LogLevel.WARN, "创建脚本流实例发生了未知错误。" + ex.ToString()); //标记为失败状态 if (scriptCaseID > 0) { BLL.EM_SCRIPT_CASE.Instance.SetFail(scriptCaseID); } return(false); } #endregion } return(true); }
/// <summary> /// 强制启动任务 /// </summary> /// <param name="taskID">任务ID</param> /// <param name="message">返回信息</param> /// <returns></returns> public bool Start(int taskID, ref string message) { try { Entity te = GetEntityByKey <Entity>(taskID); if (te == null) { message = "没有找到任务【" + taskID + "】"; return(false); } if (te.RUN_STATUS == (short)Enums.RunStatus.运行) { message = "任务正处于运行中"; return(false); } if (te.RUN_STATUS == (short)Enums.RunStatus.等待) { message = "任务正处于等待运行中,请稍后再试"; return(false); } //单节点任务 if (te.NODE_ID > 0) { BF_ST_NODE.Entity ne = BF_ST_NODE.Instance.GetEntityByKey <BF_ST_NODE.Entity>(te.NODE_ID); if (ne == null) { message = "节点任务,但没有找到节点【" + te.NODE_ID + "】"; return(false); } if (ne.RUN_STATUS == (short)Enums.RunStatus.运行) { message = "节点任务,但节点【" + ne.NAME + "】正在执行任务【" + ne.LAST_TASK_ID + "】,当前任务无法启动"; return(false); } BF_ST_NODE.Instance.SetLastTaskID(te.NODE_ID, taskID); } else { BF_ST_FLOW.Entity fe = BF_ST_FLOW.Instance.GetEntityByKey <BF_ST_FLOW.Entity>(te.FLOW_ID); if (fe == null) { message = "无效任务,但没有找到脚本【" + te.FLOW_ID + "】"; return(false); } if (fe.RUN_STATUS == (short)Enums.RunStatus.运行) { message = "脚本任务,但脚本【" + fe.NAME + "】正在执行任务【" + fe.LAST_TASK_ID + "】,当前任务无法启动"; return(false); } BF_ST_FLOW.Instance.SetLastTaskID(te.NODE_ID, taskID); } Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("RUN_STATUS", Enums.RunStatus.等待.GetHashCode()); dic.Add("UPDATE_TIME", DateTime.Now); dic.Add("START_TIME", null); dic.Add("FINISH_TIME", null); dic.Add("REMARK", "手动重启任务"); int i = Update(dic, "ID=?", taskID); if (i == 1) { message = "已重启任务,请等待执行"; return(true); } message = "启动任务失败"; } catch (Exception ex) { message = "启动任务出错,详见日志"; BLog.Write(BLog.LogLevel.WARN, "启动任务【" + taskID + "】出错:" + ex.ToString()); } return(false); }
public ActionResult ExportQuery(int dbid = 0, string sql = "") { string path = System.Web.HttpContext.Current.Server.MapPath("~/tmp/"); string fileName = string.Format("查询结果导出_{0}.txt", DateTime.Now.ToString("yyyyMMddHHmmss")); try { BLog.Write(BLog.LogLevel.DEBUG, SystemSession.UserName + "将导出查询结果到文件:" + path + fileName + ",SQL为:\r\n" + sql); if (string.IsNullOrWhiteSpace(sql)) { return(ShowAlert("请输入查询的SQL语句")); } if (sql.ToUpper().StartsWith("SELECT ") == false) { return(ShowAlert("只支持SELECT语句查询")); } if (System.IO.Directory.Exists(path) == false) { System.IO.Directory.CreateDirectory(path); } string sq = System.Web.HttpUtility.UrlDecode(sql); DataTable dt = BF_DATABASE.Instance.ExecuteSelectSQL(dbid, sq, null, 0, 1); if (dt == null) { ShowAlert("没有查到结果"); } BLog.Write(BLog.LogLevel.DEBUG, "要导的记录数为:" + dt.Rows.Count); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path + fileName, false, Encoding.UTF8)) { foreach (DataColumn col in dt.Columns) { sw.Write(col.ColumnName + "\t"); } sw.WriteLine(); foreach (DataRow dr in dt.Rows) { foreach (DataColumn col in dt.Columns) { sw.Write(Convert.ToString(dr[col]) + "\t"); } sw.WriteLine(); } } System.IO.FileInfo fi = new System.IO.FileInfo(path + fileName); BLog.Write(BLog.LogLevel.DEBUG, "文件已经生成成功,文件大小为:" + fi.Length / 1024 + "KB,即将开始下载"); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Clear();//清除缓冲区所有内容 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); System.Web.HttpContext.Current.Response.WriteFile(path + fileName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "导出查询结果出错:" + ex.ToString()); return(ShowAlert("导出查询结果出错:" + ex.Message)); } finally { if (System.IO.File.Exists(path + fileName)) { try { System.IO.File.Delete(path + fileName); BLog.Write(BLog.LogLevel.DEBUG, "导出数据的临时文件:" + path + fileName + "已经清除"); } catch (Exception e) { } } } return(null); }
// 变倍 + private void btnNear_Click(object sender, EventArgs e) { Booth.fnZoomIn(zoomStep); NoticeShow("进行放大"); BLog.ToDB("放大画面"); }
// 变倍 - private void btnFar_Click(object sender, EventArgs e) { Booth.fnZoomOut(zoomStep); NoticeShow("进行缩小"); BLog.ToDB("缩小画面"); }
private void btnCommentPath_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(config.CommentSavePath); BLog.ToDB("打开批注目录"); }
/// <summary> /// 启动 /// </summary> public static void Start() { IsRun = true; try { BLog.Write(BLog.LogLevel.INFO, "程序即将启动。"); MaxExecuteNodeCount = BConfig.GetConfigToInt("MaxExecuteNodeCount"); if (MaxExecuteNodeCount < 1) { MaxExecuteNodeCount = 10; } MaxUploadCount = BConfig.GetConfigToInt("MaxUploadCount"); EachUploadCount = BConfig.GetConfigToInt("EachUploadCount"); EachSearchUploadCount = BConfig.GetConfigToInt("EachSearchUploadCount"); MaxMonitCount = BConfig.GetConfigToInt("MaxMonitCount"); NeedClearCount = BConfig.GetConfigToInt("NeedClearCount"); //if (MaxExecuteNodeCount < 1) //{ // MaxExecuteNodeCount = 10; //} if (bool.TryParse(BConfig.GetConfigToString("KeyFieldIsAutoIncrement"), out KeyFieldIsAutoIncrement) == false) { KeyFieldIsAutoIncrement = true; } if (bool.TryParse(BConfig.GetConfigToString("KeyFieldIsUseSequence"), out KeyFieldIsUseSequence) == false) { BLog.Write(BLog.LogLevel.FATAL, "KeyFieldIsUseSequence配置不正确,请在.config中配置为true或false。"); IsRun = false; return; } if (KeyFieldIsAutoIncrement && KeyFieldIsUseSequence) { BLog.Write(BLog.LogLevel.FATAL, "KeyFieldIsAutoIncrement和KeyFieldIsUseSequence不可以同时配置为true,即:数据库已经可以自己实现自增长了,就不再需要另外配置序列,请在.config中修改配置。"); IsRun = false; return; } if (KeyFieldIsAutoIncrement == false && KeyFieldIsUseSequence == false) { BLog.Write(BLog.LogLevel.FATAL, "KeyFieldIsAutoIncrement和KeyFieldIsUseSequence不可以同时配置为false,即:数据库不能实现自增长,对于oracle和DB2来说,就需要使用序列,请在.config中修改配置。"); IsRun = false; return; } //节点任务记录器 _dicRunningNodeCaseID = new Dictionary <long, DateTime>(); lock (_dicRunningNodeCaseID) { _dicRunningNodeCaseID = new Dictionary <long, DateTime>(); } _bw = new BackgroundWorker(); _bw.WorkerSupportsCancellation = true; _bw.DoWork += bw_DoWork; _bw.RunWorkerAsync(); #region 并行+非并行:停止遗留的(等待+执行中)任务组 (2018/12/13,与非并行的处理合并) var supCaseList = BLL.EM_SCRIPT_CASE.Instance.GetNotStopCaseList(); if (supCaseList != null && supCaseList.Count > 0) { foreach (var sc in supCaseList) { BLL.EM_SCRIPT_CASE.Instance.SetStop(sc.ID, Enums.ReturnCode.Warn);//标记停止的为警告状态 } } #endregion #region 作废: 非并行:停止等待中的任务组 (2018/12/13注释,与以上并行的处理合并) //var noSupCaseList = BLL.EM_SCRIPT_CASE.Instance.GetRunningNoSuperveneCaseList(); //if (noSupCaseList != null && noSupCaseList.Count > 0) //{ // foreach (var sc in noSupCaseList) // { // BLL.EM_SCRIPT_CASE.Instance.SetStop(sc.ID, Enums.ReturnCode.Success); // } //} #endregion #region 5回复为0 using (BDBHelper dbop = new BDBHelper()) { dbop.ExecuteNonQuery(string.Format(@"update FM_MONIT_FILE set COPY_STATUS=0 where COPY_STATUS= 5")); dbop.Close();//主动关闭 } #endregion #region 重启时删除临时表FM_MONIT_FILE_TEMP_PRO FM_MONIT_FILE_TEMP using (BDBHelper dbop = new BDBHelper()) { dbop.ExecuteNonQuery(string.Format(@"truncate table FM_MONIT_FILE_TEMP")); dbop.ExecuteNonQuery(string.Format(@"truncate table FM_MONIT_FILE_TEMP_PRO")); dbop.Close();//主动关闭 } #endregion //启动手动任务线程 Task.Hand.Start(); //启动节点扫描线程(含监控任务数量的限制处理,含添加的待拷贝文件列表) Task.Scanner.Start(); BLog.Write(BLog.LogLevel.INFO, "程序已经启动。"); } catch (Exception ex) { BLog.Write(BLog.LogLevel.FATAL, "程序启动失败。" + ex.ToString()); } }
public JsonResult Template(FormCollection collection) { #region 得到参数验证数据 string formId = Request["formId"]; string op = Request["op"]; string rowKey = Request["rowKey"]; string yyyy = Request["YYYY"]; string yyyymm = Request["YYYYMM"]; string yyyymmdd = Request["YYYYMMDD"]; JsonResultData result = new JsonResultData(); if (string.IsNullOrEmpty(formId) || string.IsNullOrEmpty(op)) { result.IsSuccess = false; result.Message = "对不起!表单没有找到formId或op参数,请联系管理员。"; return(Json(result, JsonRequestBehavior.AllowGet)); } else if (op != "0" && string.IsNullOrEmpty(rowKey) == true) { result.IsSuccess = false; result.Message = "对不起!表单没有找rowKey参数值,请联系管理员。"; return(Json(result, JsonRequestBehavior.AllowGet)); } #endregion #region 提取配置信息 BF_FORM.Entity entity = BF_FORM.Instance.GetEntityByKey <BF_FORM.Entity>(formId); List <BF_FORM.FieldInfo> FieldList = JsonConvert.DeserializeObject <List <BF_FORM.FieldInfo> >(entity.FIELDS); if (FieldList.Count <= 0) { result.IsSuccess = false; result.Message = "对不起!表对应的字段有误,请联系管理员。"; return(Json(result, JsonRequestBehavior.AllowGet)); } #endregion try { List <string> strFields = new List <string>(); List <object> strValues = new List <object>(); string strMessage = ""; bool bitResult = false; if (op == "0") //数据添加 { entity.TABLE_NAME = BF_FORM.Instance.CreateTable(entity, FieldList); //动态创建数据库表 if (entity.TABLE_NAME == "") { result.IsSuccess = false; result.Message = "对不起!数据库表有误,请联系管理员。"; BLog.Write(BLog.LogLevel.WARN, "动态创建数据库表出现异常:表为空了"); return(Json(result, JsonRequestBehavior.AllowGet)); } #region 数据添加 foreach (BF_FORM.FieldInfo item in FieldList) { string val = ""; if (item.IS_INSERT == 1) { if (item.INPUT_TYPE == (int)Enums.FormInputType.显示字段) { //添加默认值 string strDefault = item.DEFAULT == null ? "" : item.DEFAULT.Trim(); if (strDefault != "") { val = BF_FORM.Instance.GetReadParam(strDefault); //将函数转为具体的值 } } else { val = collection[item.EN_NAME] == null ? "" : collection[item.EN_NAME].ToString(); if (string.IsNullOrWhiteSpace(val) && item.INPUT_TYPE == (int)Enums.FormInputType.单个复选框)//针对单个复选框由于只存在是或否的关系所以如果不选择时,有默认值,就按默认值走,如果没有就为0 { val = "0"; } } #region 数据有效性验证 string errorMessage = BF_FORM.Instance.ValidateField(item, val, rowKey, entity.DB_ID, entity.TABLE_NAME, FieldList); if (string.IsNullOrWhiteSpace(errorMessage) == false) { result.IsSuccess = false; result.Message = errorMessage; return(Json(result, JsonRequestBehavior.AllowGet)); } #endregion if (string.IsNullOrWhiteSpace(val) == false) { strFields.Add(item.EN_NAME); switch (item.FIELD_DATA_TYPE) { case (int)Enums.FieldDataType.数值: strValues.Add(Convert.ToDecimal(val)); break; case (int)Enums.FieldDataType.日期: strValues.Add(Convert.ToDateTime(val)); break; default: strValues.Add(val); break; } } } else if (item.IS_KEY_FIELD == 1 && item.IS_AUTO_INCREMENT == 0) { strFields.Add(item.EN_NAME); strValues.Add(GetNextValueFromSeqDef(entity.TABLE_NAME)); } } //entity.TABLE_NAME = BF_FORM.Instance.CreateTable(entity, FieldList);//动态创建数据库表 bitResult = BF_FORM.Instance.insertData(entity.DB_ID, entity.TABLE_NAME, strFields, strValues); #endregion } else if (op == "1")//数据更新 { #region 数据更新 strFields.Clear(); strValues.Clear(); foreach (BF_FORM.FieldInfo item in FieldList) { if (item.IS_UPDATE == 1) { strFields.Add(item.EN_NAME + "=?"); string val = ""; if (item.INPUT_TYPE == (int)Enums.FormInputType.显示字段) { //添加默认值 string strDefault = item.DEFAULT == null ? "" : item.DEFAULT.Trim(); if (strDefault != "") { val = BF_FORM.Instance.GetReadParam(strDefault); //将函数转为具体的值 } } else { val = collection[item.EN_NAME] == null ? "" : collection[item.EN_NAME].ToString(); if (string.IsNullOrWhiteSpace(val) && item.INPUT_TYPE == (int)Enums.FormInputType.单个复选框)//针对单个复选框由于只存在是或否的关系所以如果不选择时,有默认值,就按默认值走,如果没有就为0 { val = "0"; } } #region 数据有效性验证 string errorMessage = BF_FORM.Instance.ValidateField(item, val, rowKey, entity.DB_ID, entity.TABLE_NAME, FieldList); if (string.IsNullOrWhiteSpace(errorMessage) == false) { result.IsSuccess = false; result.Message = errorMessage; return(Json(result, JsonRequestBehavior.AllowGet)); } #endregion if (string.IsNullOrWhiteSpace(val))//为空时特殊处理 { if (item.FIELD_DATA_TYPE == (int)Enums.FieldDataType.数值 || item.FIELD_DATA_TYPE == (int)Enums.FieldDataType.日期) { strValues.Add(null); } else { strValues.Add(""); } } else { //添加值 switch (item.FIELD_DATA_TYPE) { case (int)Enums.FieldDataType.数值: strValues.Add(Convert.ToDecimal(val)); break; case (int)Enums.FieldDataType.日期: strValues.Add(Convert.ToDateTime(val)); break; default: strValues.Add(val); break; } } } } entity.TABLE_NAME = BF_FORM.Instance.GetTableName(entity, yyyy, yyyymm, yyyymmdd, ref strMessage);//得到动态表名 if (string.IsNullOrEmpty(strMessage) && string.IsNullOrEmpty(entity.TABLE_NAME) == false) { bitResult = BF_FORM.Instance.UpdataData(entity.DB_ID, entity.TABLE_NAME, strFields, strValues, FieldList, rowKey); } #endregion } else if (op == "2")//删除 { #region 除 entity.TABLE_NAME = BF_FORM.Instance.GetTableName(entity, yyyy, yyyymm, yyyymmdd, ref strMessage);//得到动态表名 if (string.IsNullOrEmpty(strMessage) && string.IsNullOrEmpty(entity.TABLE_NAME) == false) { bitResult = BF_FORM.Instance.DeleteData(entity.DB_ID, entity.TABLE_NAME, FieldList, rowKey); } #endregion } if (bitResult) { result.Message = "数据提交成功!"; } else { result.Message = "对不起!数据提交失败,请联系管理员。"; } result.IsSuccess = bitResult; return(Json(result, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { result.IsSuccess = false; result.Message = ex.Message; BLog.Write(BLog.LogLevel.WARN, "模板操作异常:" + ex.ToString()); } return(Json(result, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 重新加载脚本配置 /// </summary> private static void ReLoadScriptFlow() { //BLog.Write(BLog.LogLevel.DEBUG, "即将重新加载脚本。"); Dictionary <int, string> dicScripts = BLL.FW.BF_ST_FLOW.Instance.GetAllEnables(); //BLog.Write(BLog.LogLevel.DEBUG, "当前共有【" + dicScripts.Count + "】个脚本。"); int addCount = 0; int delCount = 0; int errCount = 0; int updCount = 0; //停止已经删除及停用的脚本 List <int> delTemp = new List <int>(); foreach (var kvp in _dicTaskers) { if (dicScripts.ContainsKey(kvp.Key) == false) { kvp.Value.Stop(); delTemp.Add(kvp.Key); delCount++; BLog.Write(BLog.LogLevel.DEBUG, "脚本ID【" + kvp.Key + "】已经停止。"); } } //添加新的脚本,并启动它 foreach (var kvp in dicScripts) { if (_dicTaskers.ContainsKey(kvp.Key) == true) { //更新时间表达式 if (_dicTaskers[kvp.Key].TimeExpression != kvp.Value) { _dicTaskers[kvp.Key].SetTimeExpression(kvp.Value); BLog.Write(BLog.LogLevel.INFO, string.Format("脚本【{0}】的时间表达式已经更新为【{1}】,1分钟后生效。", kvp.Key, kvp.Value)); updCount++; } } else { try { ScriptFlow sf = new ScriptFlow(kvp.Key, kvp.Value); _dicTaskers.Add(kvp.Key, sf); sf.Start(); addCount++; } catch (Exception ex) { //只输出一次错误日志,避免日志太多 if (_dicErrorTimeExpression.ContainsKey(kvp.Key) == false) { BLog.Write(BLog.LogLevel.WARN, "脚本【" + kvp.Key + "】初始化失败:" + ex.Message); _dicErrorTimeExpression.Add(kvp.Key, false); } errCount++; } } } //移除已经删除及停用的脚本 if (delTemp.Count > 0) { foreach (int id in delTemp) { _dicTaskers.Remove(id); } } if (delCount > 0 || addCount > 0 || updCount > 0) { BLog.Write(BLog.LogLevel.INFO, string.Format("已经成功重新加载脚本,删除了{0}个,成功添加了{1}个,有{2}个添加失败,更新了{3}个任务的时间表达式,当前共有{4}个计划任务,将定时执行。", delCount, addCount, errCount, updCount, _dicTaskers.Count)); } }
/// <summary> /// 为当前节点添加下级节点的实例s /// 追加流程是否结束的处理 /// </summary> /// <param name="flow"></param> /// <param name="currFlowNode"></param> /// <param name="flowCaseId"></param> /// <returns></returns> public bool CreateNextNodesCase(BF_FLOW.Entity flow, BF_FLOW_NODE.Entity currFlowNode, int flowCaseId) { bool resBool = true; try { //获得流程的所有节点信息 var allNodeList = BF_FLOW_NODE.Instance.GetList <BF_FLOW_NODE.Entity>("FLOW_ID=?", flow.ID); var allNodeJoinList = BF_FLOW_NODE_JOIN.Instance.GetList <BF_FLOW_NODE_JOIN.Entity>("FLOW_ID=?", flow.ID); //已审批通过的节点实例集合 var allNodeCaseList = BF_FLOW_NODE_CASE.Instance.GetList <BF_FLOW_NODE_CASE.Entity>("FLOW_ID=? AND FLOW_CASE_ID=? AND AUDIT_STATUS=?", flow.ID, flowCaseId, CS.Common.Enums.AuditStatus.通过.GetHashCode()); //先获得当前节点下个走向节点集合 var nodeJoinList = allNodeJoinList.Where(p => p.FROM_NODE_ID == currFlowNode.ID).ToList(); //var nodeJoinList = BF_FLOW_NODE_JOIN.Instance.GetList<BF_FLOW_NODE_JOIN.Entity>("FLOW_ID=? AND FROM_NODE_ID=?", flow.ID, mainNode.ID); if (nodeJoinList != null && nodeJoinList.Count > 0) { //分别为下级节点添加待办,分别为其创建待处理节点(暂时只考虑具体到人的情况) foreach (var toNode in nodeJoinList) { var curFromNodeIdList = allNodeJoinList.Where(p => p.TO_NODE_ID == toNode.ID).Select(p => p.FROM_NODE_ID).ToList(); var ncCount = allNodeCaseList.Count(p => curFromNodeIdList.Contains(p.FLOW_NODE_ID)); if (curFromNodeIdList.Count == ncCount)//from节点数=from节点实例数,添加下级待办 { var curToNode = allNodeList.FirstOrDefault(p => p.ID == toNode.TO_NODE_ID); int curToNodeCase = BF_FLOW_NODE_CASE.Instance.AddFlowNodeCase(curToNode, flowCaseId, flow.ID, toNode.FROM_NODE_ID); } } } else { //验证流程是否结束(末梢节点是否均处理完毕) if (ValidateFlowCaseIsFinish(flow.ID, flowCaseId)) { string remark = null; //结束流程 var flowCase = BF_FLOW_CASE.Instance.GetEntityByKey <BF_FLOW_CASE.Entity>(flowCaseId); flowCase.IS_ARCHIVE = 1; flowCase.IS_ENABLE = 1; flowCase.ARCHIVE_TIME = DateTime.Now; BF_FLOW_CASE.Instance.UpdateByKey(flowCase, flowCaseId); //验证和触发下个流程 var flowRefList = BF_FLOW_REF.Instance.GetNextFlow(flow.ID); if (flowRefList != null && flowRefList.Count > 0) { foreach (var flowRef in flowRefList) { CreateFlowCaseAndMainNodeCase(flowRef.FLOW_ID); } remark = string.Format(@"创建了[{0}]个下级流程", flowRefList.Count); } else { remark = "未找到下级走向节点"; } #region 加入走向说明 Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("REMARK", remark);//是否流程就结束了呢? BF_FLOW_CASE.Instance.UpdateByKey(dic, flowCaseId); #endregion } } } catch (Exception ex) { string errMsg = string.Format(@"为流程[{0}]实例[{1}]的节点[{2}]添加下级节点实例失败:{3}", flow.ID, flowCaseId, currFlowNode.ID, ex.Message); BLog.Write(BLog.LogLevel.ERROR, errMsg); throw new Exception(errMsg); } return(resBool); }
/// <summary> /// 获取下拉单元框的选项列表 /// </summary> /// <param name="entity">实体</param> /// <returns></returns> public static Dictionary <string, string> GetSelectOptions(Entity entity) { Dictionary <string, string> options = new Dictionary <string, string>(); if (entity == null || entity.FORM_QUERY_TYPE != (short)Enums.FormQueryType.拉单选框 || string.IsNullOrWhiteSpace(entity.SELECT_DETAIL)) { return(options); } string[] selectDetail = entity.SELECT_DETAIL.Split(new char[] { ':' }); if (selectDetail.Length < 2) { return(options); } if (selectDetail[0] == Enums.FormSelectType.枚举值.GetHashCode().ToString()) { string[] ops = selectDetail[1].Split(new char[] { '\r', '\n', ';', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string op in ops) { string[] os = op.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); if (os.Length != 2) { continue; } if (options.ContainsKey(os[0]) == false) { string k = BF_FORM.Instance.GetReadParam(os[0]); string v = BF_FORM.Instance.GetReadParam(os[1]); options.Add(k, v); } } } else if (selectDetail[0] == Enums.FormSelectType.表查询.GetHashCode().ToString()) { string[] infos = selectDetail[1].Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); if (infos.Length < 4) { return(options); } int dbid = 0; if (int.TryParse(infos[0], out dbid) == false) { return(options); } string where = "1=1"; if (infos.Length > 4 && string.IsNullOrWhiteSpace(infos[4]) == false) { where = infos[4]; } try { int rowsCount = -1; string sql = string.Format("SELECT {0} KKK,{1} VVV FROM {2} WHERE {3}", infos[2], infos[3], infos[1], where); sql = BF_FORM.Instance.GetReadParam(sql); DataTable dt = BF_DATABASE.Instance.ExecuteSelectSQL(dbid, sql, null, ref rowsCount, 0); if (dt != null) { foreach (DataRow dr in dt.Rows) { if (dr[0] == DBNull.Value || dr[1] == DBNull.Value) { continue; } string key = Convert.ToString(dr[0]); if (options.ContainsKey(key) == false) { options.Add(key, Convert.ToString(dr[1])); } } } } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "加载报表" + entity.REPORT_ID + ",筛选字段" + entity.FIELD_NAME + "的下拉筛选项出错:" + ex.ToString()); } } else if (selectDetail[0] == Enums.FormSelectType.SQL语句.GetHashCode().ToString()) { string[] infos = selectDetail[1].Split('◎'); if (infos.Length < 2) { return(options); } int dbid = 0; if (int.TryParse(infos[0], out dbid) == false) { return(options); } string sql = infos[1];//得到SQL语句 if (string.IsNullOrWhiteSpace(sql) == false) { sql = BF_FORM.Instance.GetReadParam(sql); int rowsCount = -1; DataTable dt = BF_DATABASE.Instance.ExecuteSelectSQL(dbid, sql, null, ref rowsCount, 0); if (dt != null) { foreach (DataRow dr in dt.Rows) { if (dr[0] == DBNull.Value || dr[1] == DBNull.Value) { continue; } string key = Convert.ToString(dr[0]); if (options.ContainsKey(key) == false) { options.Add(key, Convert.ToString(dr[1])); } } } } } return(options); }
private DataTable SelectItem(BF_FORM.FieldInfo fieldData) { if (fieldData == null) { return(null); } DataTable opData = new DataTable(); switch (fieldData.SELECT_INPUT_TYPE) { case (int)FormSelectType.枚举值: opData.Columns.Add("k"); opData.Columns.Add("v"); if (fieldData.INPUT_TYPE == (int)FormInputType.拉树选择) { opData.Columns.Add("p"); } List <SelectEnumOption> op = fieldData.SELECT_ENUM_OPTIONS; if (op != null && op.Count > 0) { foreach (SelectEnumOption item in op) { DataRow row = opData.NewRow(); row["k"] = GetReadParam(item.NAME); row["v"] = GetReadParam(item.VALUE); if (fieldData.INPUT_TYPE == (int)FormInputType.拉树选择) { row["p"] = (string.IsNullOrWhiteSpace(item.PID) ? "0" : item.PID); } opData.Rows.Add(row); } } break; case (int)FormSelectType.表查询: string pidField = ""; if (fieldData.INPUT_TYPE == (int)FormInputType.拉树选择) { pidField = "," + fieldData.SELECT_QUERY_INFO.PID_FIELD + " p "; } string strField = fieldData.SELECT_QUERY_INFO.NAME_FIELD + " k," + fieldData.SELECT_QUERY_INFO.VALUE_FIELD + " v" + pidField; //需要查询的字段 string strWhere = fieldData.SELECT_QUERY_INFO.WHERE; strWhere = GetReadParam(strWhere); //得到SQL opData = GetData(fieldData.SELECT_QUERY_INFO.DB_ID, fieldData.SELECT_QUERY_INFO.TABLE_NAME, strField, strWhere); break; case (int)FormSelectType.SQL语句: if (string.IsNullOrWhiteSpace(fieldData.SQL) == false) { string[] info = fieldData.SQL.Split('◎'); if (info.Length < 2 || string.IsNullOrWhiteSpace(info[0]) || string.IsNullOrWhiteSpace(info[1])) { return(null); } try { string strSql = GetReadParam(info[1]); //得到SQL opData = BF_DATABASE.Instance.ExecuteSelectSQL(Convert.ToInt32(info[0]), strSql, null, 0, 1); } catch (Exception ex) { BLog.Write(BLog.LogLevel.ERROR, "保存SQL模式时,出现未知错误:" + ex.ToString()); return(null); } } break; } return(opData); }
/// <summary> /// 导出文件附件 /// </summary> /// <param name="wherestr">搜索条件</param> /// <returns>附件信息</returns> public ActionResult ExportFile(string name = "", int runState = -1, int isEnable = -1, int lastTaskIs = -1, int self = 0) { try { string filename = HttpUtility.UrlEncode(string.Format("导出报表_脚本任务_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")), System.Text.Encoding.UTF8); string path = System.Web.HttpContext.Current.Server.MapPath("~/tmp/"); string where = "1=1"; List <object> param = new List <object>(); #region 添加参数 if (!string.IsNullOrWhiteSpace(name)) { where += " AND NAME LIKE '%" + name.Replace('\'', ' ') + "%'"; } if (runState > -1) { where += " AND RUN_STATUS = " + runState; } if (isEnable > -1) { where += " AND IS_ENABLE = " + isEnable; } if (lastTaskIs > -1) { where += " AND LAST_TASK_IS =" + lastTaskIs; } if (self > 0) { where += " AND CREATE_UID = " + SystemSession.UserID; } #endregion var dt = BLL.FW.BF_ST_FLOW.Instance.GetTableFields("ID,NAME,TYPE_ID,CRON,RETRY_TIMES,IS_ENABLE,RUN_STATUS,LAST_TASK_IS,LAST_TASK_ID", where, param); if (dt == null) { return(ShowAlert("导出数据到Excel出现错误:未查询出数据")); } dt.Columns.Remove("ID"); dt.Columns["NAME"].Caption = "脚本流名称"; dt.Columns["TYPE_ID"].Caption = "脚本流类型"; dt.Columns["CRON"].Caption = "时间表达式"; dt.Columns["RETRY_TIMES"].Caption = "失败重试次数"; dt.Columns["IS_ENABLE"].Caption = "是否启用"; dt.Columns["RUN_STATUS"].Caption = "运行状态"; dt.Columns["LAST_TASK_IS"].Caption = "最新任务是否成功"; dt.Columns["LAST_TASK_ID"].Caption = "最新任务ID"; Library.Export.ExcelFile export = new Library.Export.ExcelFile(path); string fullName = export.ToExcel(dt); if (string.IsNullOrWhiteSpace(fullName) == true) { return(ShowAlert("未生成Excel文件")); } System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Clear();//清除缓冲区所有内容 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); System.Web.HttpContext.Current.Response.WriteFile(fullName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); //删除文件 export.Delete(fullName); } catch (Exception ex) { BLog.Write(BLog.LogLevel.WARN, "导出默认报表[DB]到Excel出错:" + ex.ToString()); return(ShowAlert("导出数据到Excel出现未知错误:" + ex.Message)); } return(ShowAlert("导出成功")); }
public string CreateTable(BF_FORM.Entity entity, List <BF_FORM.FieldInfo> FieldList) { #region 计算表名 short tableMode = entity.CREATE_TABLE_MODE; string tableName = entity.TABLE_NAME; #region 数据库对像 BDBHelper dbHelper = null; if (entity.DB_ID == 0) { dbHelper = new BDBHelper(); } else { BF_DATABASE.Entity db = BF_DATABASE.Instance.GetEntityByKey <BF_DATABASE.Entity>(entity.DB_ID); if (db == null) { BLog.Write(BLog.LogLevel.WARN, "查询数据库对像出现异常:数据库ID" + entity.DB_ID); return(""); } string dbType = BF_DATABASE.GetDbTypeName(db.DB_TYPE); dbHelper = new BDBHelper(dbType, db.IP, db.PORT, db.USER_NAME, db.PASSWORD, db.DB_NAME, db.DB_NAME); } #endregion //如查指定的表存在就返回 if (entity.CREATE_TABLE_MODE == (short)Enums.CreateTableMode.指定表 && dbHelper.TableIsExists(tableName)) { return(tableName); } switch (tableMode) { case (short)Enums.CreateTableMode.年份后缀: tableName += "_" + DateTime.Now.ToString("yyyy"); break; case (short)Enums.CreateTableMode.年月后缀: tableName += "_" + DateTime.Now.ToString("yyyyMM"); break; case (short)Enums.CreateTableMode.年月日后缀: tableName += "_" + DateTime.Now.ToString("yyyyMMdd"); break; case (short)Enums.CreateTableMode.用户ID后缀: tableName += "_" + SystemSession.UserID; break; } #endregion #region 建表 //自增长主键 string autoIncrementField = string.Empty; //唯一约束字段 string uniqueField = string.Empty; //唯一约束的值 // Dictionary<string, bool> dicUniqueValues = new Dictionary<string, bool>(); foreach (var field in FieldList) { if (field.IS_AUTO_INCREMENT == 1) { autoIncrementField = field.EN_NAME; } if (field.IS_UNIQUE == 1) { uniqueField = field.EN_NAME; } } //表不存在 if (entity.CREATE_TABLE_MODE != (short)Enums.CreateTableMode.指定表 && dbHelper.TableIsExists(tableName) == false) { //创建表 if (dbHelper.CreateTable(tableName, entity.TABLE_NAME) == false) { BLog.Write(BLog.LogLevel.WARN, "动态建表出现异常:" + tableName); return(""); } //设置自增长 if (dbHelper.SetAutoIncrement(tableName, autoIncrementField) == false) { BLog.Write(BLog.LogLevel.WARN, "设置表" + tableName + "的字段" + autoIncrementField + "为自增长失败"); return(""); } } #endregion return(tableName); }
public JsonResult Edit(BF_FILE.Entity entity, FormCollection collection) { JsonResultData result = new JsonResultData(); int i = 0; try { if (entity.ID < 0) { result.Message = "配置项不存在,不可编辑"; return(Json(result, JsonRequestBehavior.AllowGet)); } entity.UPDATE_UID = SystemSession.UserID; entity.UPDATE_TIME = DateTime.Now; if (string.IsNullOrWhiteSpace(collection["ACCEPT_FILE_TYPES"]) == true) { entity.ACCEPT_FILE_TYPES = Enums.AcceptUploadFileType.限.GetHashCode().ToString(); } else { entity.ACCEPT_FILE_TYPES = collection["ACCEPT_FILE_TYPES"]; } if (entity.ID == 0) { entity.IS_ENABLE = 1; entity.CREATE_UID = SystemSession.UserID; entity.CREATE_TIME = DateTime.Now; i = BF_FILE.Instance.Add(entity); } else { Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("NAME", entity.NAME); dic.Add("DB_ID", entity.DB_ID); dic.Add("TABLE_NAME", entity.TABLE_NAME); dic.Add("CREATE_TABLE_MODE", entity.CREATE_TABLE_MODE); dic.Add("KEY_FIELD", entity.KEY_FIELD); dic.Add("IS_ALLOW_DELETE", entity.IS_ALLOW_DELETE); dic.Add("ACCEPT_FILE_TYPES", entity.ACCEPT_FILE_TYPES); dic.Add("REMARK", entity.REMARK); dic.Add("UPDATE_UID", entity.UPDATE_UID); dic.Add("UPDATE_TIME", entity.UPDATE_TIME); i = BF_FILE.Instance.UpdateByKey(dic, entity.ID); } if (i < 1) { result.Message = "出现了未知错误"; return(Json(result, JsonRequestBehavior.AllowGet)); } result.IsSuccess = true; result.Message = "保存成功"; WriteOperationLog(BLog.LogLevel.WARN, false, Modular, "编辑", "", (entity.ID > 0 ? "修改" : "添加") + "ID为" + entity.ID + "的配置失败"); } catch (Exception ex) { result.IsSuccess = false; result.Message = ex.Message; BLog.Write(BLog.LogLevel.WARN, "编辑附件配置出错:" + ex.ToString()); WriteOperationLog(BLog.LogLevel.INFO, true, Modular, "编辑", "", (entity.ID > 0 ? "修改" : "添加") + "了ID为" + entity.ID + "的配置"); } return(Json(result, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 导入数据文件 /// </summary> /// <param name="entity">实体</param> /// <param name="fileName">文件名</param> /// <param name="baseDate">基准日期</param> /// <param name="message">返回信息</param> /// <param name="errorList">错误信息(键:行号,值:错误信息)</param> /// <returns></returns> public static int ImportDataFile(Entity entity, string fileName, DateTime baseDate, out string message, out Dictionary <int, string> errorList) { int n = 0; int loadCount = 0; int updateCount = 0; message = string.Empty; errorList = new Dictionary <int, string>(); try { if (entity == null) { message = "配置不存在"; return(n); } if (File.Exists(fileName) == false) { message = "文件" + fileName + "不存在"; return(n); } string tableName = entity.TABLE_NAME; switch (entity.CREATE_TABLE_MODE) { case (short)Enums.CreateTableMode.年份后缀: tableName += "_" + baseDate.ToString("yyyy"); break; case (short)Enums.CreateTableMode.年月后缀: tableName += "_" + baseDate.ToString("yyyyMM"); break; case (short)Enums.CreateTableMode.年月日后缀: tableName += "_" + baseDate.ToString("yyyyMMdd"); break; case (short)Enums.CreateTableMode.用户ID后缀: tableName += "_" + SystemSession.UserID; break; } string sqlQuery = "SELECT * FROM {0} WHERE 1=0"; string sqlUnique = "SELECT {0} FROM {1}"; //字段配置 Dictionary <string, FieldInfo> dicFields = GetFieldsInfo(entity.FIELDS); //自增长主键 string autoIncrementField = string.Empty; //忽略的字段 Dictionary <string, bool> dicIgnore = new Dictionary <string, bool>(); //唯一约束字段 string uniqueField = string.Empty; //唯一约束的值 Dictionary <string, bool> dicUniqueValues = new Dictionary <string, bool>(); foreach (var kvp in dicFields) { if (kvp.Value.IS_AUTO_INCREMENT == 1) { autoIncrementField = kvp.Key; } if (kvp.Value.IS_IMPORT == 0) { dicIgnore.Add(kvp.Key, true); } if (kvp.Value.IS_UNIQUE == 1) { uniqueField = kvp.Key; } } BDBHelper dbHelper = null; try { if (entity.DB_ID == 0) { dbHelper = new BDBHelper(); } else { BF_DATABASE.Entity db = BF_DATABASE.Instance.GetEntityByKey <BF_DATABASE.Entity>(entity.DB_ID); if (db == null) { message = "数据库" + entity.DB_ID + "不存在"; return(n); } string dbType = BF_DATABASE.GetDbTypeName(db.DB_TYPE); dbHelper = new BDBHelper(dbType, db.IP, db.PORT, db.USER_NAME, db.PASSWORD, db.DB_NAME, db.DB_NAME); } //表不存在 if (entity.CREATE_TABLE_MODE != (short)Enums.CreateTableMode.指定表 && dbHelper.TableIsExists(tableName) == false) { //创建表 if (dbHelper.CreateTable(tableName, entity.TABLE_NAME) == false) { message = "创建表" + tableName + "失败"; return(n); } //设置自增长 if (string.IsNullOrWhiteSpace(autoIncrementField) == false) { if (dbHelper.SetAutoIncrement(tableName, autoIncrementField) == false) { message = "设置表" + tableName + "的字段" + autoIncrementField + "为自增长失败"; return(n); } } } //查询需要导入的字段 DataTable dtQuery = dbHelper.ExecuteDataTable(string.Format(sqlQuery, tableName)); if (dtQuery == null) { message = "无法查询导入的目标表" + tableName; return(n); } //是否包含导入用户ID bool isContainsUid = dtQuery.Columns.Contains("IMPORT_UID"); //是否包含导入时间 bool isContainsTime = dtQuery.Columns.Contains("IMPORT_TIME"); //读取Excel中的数据 DataTable tdExcel = new DataTable(); foreach (DataColumn col in dtQuery.Columns) { if (dicIgnore.ContainsKey(col.ColumnName.ToUpper())) { continue; } tdExcel.Columns.Add(col.ColumnName, col.DataType); } //读取数据到DataTable if (LoadFileIntoDataTable(fileName, ref tdExcel, out message) == false) { return(0); } if (tdExcel.Rows.Count < 1) { message = "没有数据"; return(0); } //要导入的数据 DataTable tdLoad = new DataTable(); DataTable tdUpdate = new DataTable(); foreach (DataColumn colExcel in tdExcel.Columns) { tdLoad.Columns.Add(colExcel.ColumnName.ToUpper(), colExcel.DataType); tdUpdate.Columns.Add(colExcel.ColumnName.ToUpper(), colExcel.DataType); } if (isContainsUid == true) { tdLoad.Columns.Add("IMPORT_UID", typeof(int)); tdUpdate.Columns.Add("IMPORT_UID", typeof(int)); } if (isContainsTime == true) { tdLoad.Columns.Add("IMPORT_TIME", typeof(DateTime)); tdUpdate.Columns.Add("IMPORT_TIME", typeof(DateTime)); } tdUpdate.Columns.Add("EXCEL_ROW_NUM", typeof(int)); //唯一约束 bool isCheckUnique = false; if (string.IsNullOrWhiteSpace(uniqueField) == false) { sqlUnique = string.Format(sqlUnique, uniqueField, tableName); DataTable tdUnique = dbHelper.ExecuteDataTable(sqlUnique); if (tdUnique != null) { foreach (DataRow rowUnique in tdUnique.Rows) { string key = Convert.ToString(rowUnique[0]); if (dicUniqueValues.ContainsKey(key) == false) { dicUniqueValues.Add(key, true); isCheckUnique = true; } } } } //将数据分别写入待导入及待更新 int excelRowNumber = 1; //本批次数据重复性验证 bool isContainsUniqueField = tdExcel.Columns.Contains(uniqueField); Dictionary <string, bool> dicTemp = new Dictionary <string, bool>(); List <int> errorTemp = new List <int>(); DateTime importTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); foreach (DataRow dr in tdExcel.Rows) { excelRowNumber++; string key = string.Empty; if (string.IsNullOrWhiteSpace(uniqueField) == false && isContainsUniqueField == true) { key = Convert.ToString(dr[uniqueField]); //不可为空 if (string.IsNullOrWhiteSpace(key) == true) { errorTemp.Add(excelRowNumber); } //本批次要导入的数据重复 if (dicTemp.ContainsKey(key)) { errorTemp.Add(excelRowNumber); continue; } dicTemp.Add(key, true); //和数据库里面原有数据比较 if (isCheckUnique == true) { //违反唯一约束 if (dicUniqueValues.ContainsKey(key)) { DataRow updateRow = tdUpdate.NewRow(); foreach (DataColumn updateCol in tdExcel.Columns) { updateRow[updateCol.ColumnName] = dr[updateCol]; } if (isContainsUid == true) { updateRow["IMPORT_UID"] = SystemSession.UserID; } if (isContainsTime == true) { updateRow["IMPORT_TIME"] = importTime; } updateRow["EXCEL_ROW_NUM"] = excelRowNumber; tdUpdate.Rows.Add(updateRow); errorList.Add(excelRowNumber, "数据库中已经存在值:" + key); continue; } } } //加入待插入 DataRow insertRow = tdLoad.NewRow(); foreach (DataColumn insertCol in tdExcel.Columns) { insertRow[insertCol.ColumnName] = dr[insertCol]; } if (isContainsUid == true) { insertRow["IMPORT_UID"] = SystemSession.UserID; } if (isContainsTime == true) { insertRow["IMPORT_TIME"] = importTime; } tdLoad.Rows.Add(insertRow); } //导入数据 if (tdLoad.Rows.Count > 0) { try { loadCount = dbHelper.LoadDataInDataTable(tableName, tdLoad); message = string.Format("共导入{0}条数据", loadCount); } catch (Exception el) { message = string.Format("尝试导入{0}条数据出错:{1}", tdLoad.Rows.Count, el.Message); } } //更新数据 if (tdUpdate.Rows.Count > 0) { if (entity.IS_ALLOW_UPDATE == 1) { errorList = new Dictionary <int, string>(); string updateFields = string.Empty; int ui = 0; foreach (DataColumn col in tdUpdate.Columns) { if (col.ColumnName == uniqueField || col.ColumnName == "EXCEL_ROW_NUM") { continue; } if (ui == 0) { updateFields += col.ColumnName + "=?"; } else { updateFields += " ," + col.ColumnName + "=?"; } ui++; } string sqlUpdate = string.Format("UPDATE {0} SET {1} WHERE {2}=?", tableName, updateFields, uniqueField); foreach (DataRow drUpdate in tdUpdate.Rows) { List <object> values = new List <object>(); foreach (DataColumn col in tdUpdate.Columns) { if (col.ColumnName == uniqueField || col.ColumnName == "EXCEL_ROW_NUM") { continue; } values.Add(drUpdate[col]); } values.Add(drUpdate[uniqueField]); if (dbHelper.ExecuteNonQueryParams(sqlUpdate, values) > 0) { updateCount++; } else { errorList.Add(Convert.ToInt32(drUpdate["EXCEL_ROW_NUM"]), "更新数据失败"); } } } } foreach (int row in errorTemp) { errorList.Add(row, "表格中数据重复"); } if (updateCount > 0) { message += ",更新" + updateCount + "条"; } if (errorList.Count > 0) { message += ",失败" + errorList.Count + "条"; } } catch (Exception e) { message += "导入数据出错:" + e.Message; BLog.Write(BLog.LogLevel.WARN, "外导数据出错:" + e.ToString()); return(loadCount + updateCount); } finally { if (dbHelper != null) { dbHelper.Dispose(); } } } catch (Exception ex) { message += "导入数据出错:" + ex.Message; BLog.Write(BLog.LogLevel.WARN, "外导数据出错:" + ex.ToString()); return(loadCount + updateCount); } return(loadCount + updateCount); }
/// <summary> /// 往待拷贝列表中加入文件编号 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void DoWork2(object sender, DoWorkEventArgs e) { while (Main.IsRun) { try { #region 再次验证和清理未在线终端 //var ipArr = global.ipList.ToArray(); //for (int i = 0; i < ipArr.Count(); i++) //{ // if (Request.PingIP(ipArr[i].Value) && global.ipList.ContainsKey(ipArr[i].Key)) // { // global.ipList.Remove(ipArr[i].Key);//移除已在线的终端 // } //} var ipNotLists = global.OpIpNotList("getall"); if (ipNotLists != null && ipNotLists.Count > 0) { int cnt = ipNotLists.Count; for (int i = cnt - 1; i >= 0; i--) { var item = ipNotLists[i]; if (Librarys.ApiRequest.Request.OldPingIP(item.V)) { global.OpIpNotList("remove", item); } } ipNotLists = global.OpIpNotList("getall"); BLog.Write(BLog.LogLevel.INFO, "输出未在线的ip:" + string.Join(",", ipNotLists.Select(p => p.V))); } #endregion BLog.Write(BLog.LogLevel.INFO, "已在列表中的数量:" + global.GetMonitKVCount()); if (global.GetEffectMonitKVCount() < 200) //if (global.GetMonitKVCount() < 200) { //var ipNotLists = global.OpIpNotList("getall"); #region 获取MaxUploadCount条待拷贝记录(排除未在线终端) //采集待插入的文件列表 //采集未在线的终端列表 //lcz, 这个地方的sql可以只返回同一客户机ip的,便于下面的一个连接多个文件拷贝 //获取不返回一个ip的文件,在从monitKVList中获取5个一样ip的终端去处理 //string sql = string.Format(@"SELECT A.ID, B.IP, A.COMPUTER_ID // FROM (SELECT ID, COMPUTER_ID // FROM (SELECT A.ID, // A.COMPUTER_ID, // ROW_NUMBER () OVER (ORDER BY A.ID) RN // FROM FM_MONIT_FILE A // LEFT JOIN ( SELECT DISTINCT REGEXP_SUBSTR ('{0}', // '[^,]+', // 1, // LEVEL) // AS COMPUTER_ID // FROM DUAL // CONNECT BY REGEXP_SUBSTR ('{0}', // '[^,]+', // 1, // LEVEL) // IS NOT NULL) C // ON (A.COMPUTER_ID = C.COMPUTER_ID) // LEFT JOIN FM_FILE_FORMAT F ON (F.ID=A.FILE_FORMAT_ID) // WHERE NVL (C.COMPUTER_ID, 0) = 0 AND F.NAME<>'Folder' // AND (A.COPY_STATUS = 0 OR A.COPY_STATUS = 3)) // WHERE RN <={1}) A // LEFT JOIN FM_COMPUTER B ON (A.COMPUTER_ID = B.ID)", string.Join(",", ipNotLists.Select(p => p.K).Distinct()), Main.EachSearchUploadCount); string sql = string.Format(@"SELECT A.ID, B.IP, A.COMPUTER_ID FROM (SELECT A.ID, A.COMPUTER_ID FROM FM_MONIT_FILE A LEFT JOIN ( SELECT DISTINCT REGEXP_SUBSTR ('{0}', '[^,]+', 1, LEVEL) AS COMPUTER_ID FROM DUAL CONNECT BY REGEXP_SUBSTR ('{0}', '[^,]+', 1, LEVEL) IS NOT NULL) C ON (A.COMPUTER_ID = C.COMPUTER_ID) LEFT JOIN FM_FILE_FORMAT F ON (F.ID = A.FILE_FORMAT_ID) WHERE NVL (C.COMPUTER_ID, 0) = 0 AND F.NAME <> 'Folder' AND (A.COPY_STATUS = 0 OR A.COPY_STATUS = 3) AND ROWNUM <= {1}) A LEFT JOIN FM_COMPUTER B ON (A.COMPUTER_ID = B.ID)", string.Join(",", ipNotLists.Select(p => p.K).Distinct()), Main.EachSearchUploadCount); StringBuilder sb = new StringBuilder(); //待处理 //StringBuilder sbNotAlive = new StringBuilder();//未在线 List <string> notAliveList = new List <string>(); //当前查询的未在线 DataTable dt = null; using (BDBHelper dbop = new BDBHelper()) { dt = dbop.ExecuteDataTable(sql); if (dt != null && dt.Rows.Count > 0) { string updateSql = string.Format(@"update FM_MONIT_FILE set COPY_STATUS=5 where id in({0})", string.Join(",", dt.AsEnumerable().Select(r => r["ID"]).Distinct().ToArray()).TrimEnd(',')); dbop.ExecuteNonQuery(updateSql); } dbop.Close(); } //log("查询出的数量为:【" + dt.Rows.Count + "】"); BLog.Write(BLog.LogLevel.INFO, "查询出的数量为:【" + dt.Rows.Count + "】"); if (dt != null && dt.Rows.Count > 0) { List <string> hasAliveIps = new List <string>();//当前批次的在线ip for (int i = 0; i < dt.Rows.Count; i++) { sb.Append(dt.Rows[i][0] + ","); //校验ip string curIp = dt.Rows[i][1].ToString().Trim(); //log("当前ip【" + curIp + "】"); var curKv = new KV { K = Convert.ToInt64(dt.Rows[i][2].ToString()), V = dt.Rows[i][1].ToString() }; //不在线的ip if (string.IsNullOrEmpty(curIp)) { BLog.Write(BLog.LogLevel.INFO, "文件编号:" + dt.Rows[i][0] + "为空"); //log("ip[" + curIp + "]为空");//20180701注释 //BLog.Write(BLog.LogLevel.INFO, "ip[" + curIp + "]为空"); } else if (hasAliveIps.Contains(curIp)) { BLog.Write(BLog.LogLevel.INFO, "文件编号:" + dt.Rows[i][0] + "IP在线"); global.OpMonitKVList("add", new KV { K = Convert.ToInt64(dt.Rows[i][0].ToString()), V = dt.Rows[i][1].ToString() }); //20180701注释 //log("ip[" + curIp + "]在已在线列表中"); } else { if (ipNotLists.Exists(p => p.K == curKv.K)) { BLog.Write(BLog.LogLevel.INFO, "文件编号:" + dt.Rows[i][0] + "IP不在线"); //log("ip[" + curIp + "]未在线2"); using (BDBHelper dbop = new BDBHelper()) { string updateSql = string.Format(@"update FM_MONIT_FILE set COPY_STATUS=0 where id ={0}", dt.Rows[i][0].ToString()); dbop.ExecuteNonQuery(updateSql); dbop.Close(); } if (!notAliveList.Contains(curKv.V)) { notAliveList.Add(curKv.V); } } else if (!Request.PingIP(curIp)) { BLog.Write(BLog.LogLevel.INFO, "文件编号2:" + dt.Rows[i][0] + "IP不在线"); //log("ip[" + curIp + "]未在线"); using (BDBHelper dbop = new BDBHelper()) { string updateSql = string.Format(@"update FM_MONIT_FILE set COPY_STATUS=0 where id ={0}", dt.Rows[i][0].ToString()); dbop.ExecuteNonQuery(updateSql); dbop.Close(); } global.OpIpNotList("add", curKv); notAliveList.Add(dt.Rows[i][1].ToString()); if (!ipNotLists.Exists(p => p.K == curKv.K)) { ipNotLists.Add(curKv); } } else { global.OpMonitKVList("add", new KV { K = Convert.ToInt64(dt.Rows[i][0].ToString()), V = dt.Rows[i][1].ToString() }); hasAliveIps.Add(curIp); BLog.Write(BLog.LogLevel.INFO, "文件编号:" + dt.Rows[i][0] + "添加文件"); //log("ip[" + curIp + "]在线"); //BLog.Write(BLog.LogLevel.INFO, "ip[" + curIp + "]在线");//20180701注释 } } } //log("再次输出未在线ip:" + string.Join(",", global.OpIpNotList("getall").Select(p => p.V))); #endregion //log("内存中无监控的文件列表,从数据库中去获取", 4, string.Format(@"执行查询的sql:\r\n{0}。\r\n查询的结果为:{1}", sql, sb)); BLog.Write(BLog.LogLevel.INFO, "内存中无监控的文件列表,从数据库中去获取." + string.Format(@"执行查询的sql:\r\n{0}。\r\n查询的结果为:{1}", sql, sb)); BLog.Write(BLog.LogLevel.INFO, "获取到未在线的ip【" + (notAliveList.Count > 0 ? string.Join(",", notAliveList.Distinct()) : "") + "】,当前未在线的ip列表为【" + string.Join(" , ", global.ipNotList.Select(p => p.V)) + "】"); //log("获取到未在线的ip【" + (notAliveList.Count > 0 ? string.Join(",", notAliveList.Distinct()) : "") + "】,当前未在线的ip列表为【" + string.Join(" , ", global.ipNotList.Select(p => p.V)) + "】"); } else { //string msg = "未在库中查询到需要拷贝的文件,当前不存在需拷贝文件"; //log(msg); //log(msg, 3, string.Format(@"执行查询的sql:\r\n{0}。", sql)); BLog.Write(BLog.LogLevel.INFO, string.Format(@"执行查询的sql:\r\n{0}。", sql)); //return null; } } } catch (Exception ex) { BLog.Write(BLog.LogLevel.ERROR, "查询添加待拷贝文件出错:" + ex.ToString()); } Thread.Sleep(2000); } }
// 停止 void RecordStop() { m_csAVFrm.stopRecordMp4(rtspRecorderId); BLog.ToDB("停止录像"); }