public static void MiddleTableImport() { string cmdText = "SELECT * FROM ZJIANWEN WHERE FLAG=0"; string str2 = " INSERT INTO MiddleTable VALUES(@PrjCode,@ContractCode,@SerialNumber,\r\n @Belnr,@MoneyAmount,@Tag,@Hkont,@Flag,@Buzet,@F_date,@Txt)"; try { OleDbDataReader reader = ExecuteReader(CommandType.Text, cmdText, null); while (reader.Read()) { string serialNumber = DBHelper.GetString(reader["SERIAL"]); decimal @decimal = DBHelper.GetDecimal(reader["MONEY"]); if (IsExist(serialNumber)) { SqlHelper.ExecuteNonQuery(CommandType.Text, str2, new List <SqlParameter> { new SqlParameter("@PrjCode", DBHelper.GetString(reader["PROJNO"])), new SqlParameter("@ContractCode", DBHelper.GetString(reader["HETONG"])), new SqlParameter("@SerialNumber", serialNumber), new SqlParameter("@Belnr", DBHelper.GetString(reader["BELNR"])), new SqlParameter("@MoneyAmount", DBHelper.GetDecimal(reader["MONEY"])), new SqlParameter("@Tag", DBHelper.GetString(reader["TAG"])), new SqlParameter("@Hkont", DBHelper.GetString(reader["HKONT"])), new SqlParameter("@Flag", DBHelper.GetBool(reader["FLAG"])), new SqlParameter("@Buzet", DBHelper.GetInt(reader["BUZEI"])), new SqlParameter("@F_date", DBHelper.GetDateTimeNullable(reader["F_DATE"])), new SqlParameter("@Txt", DBHelper.GetString(reader["WENBEN"])) }.ToArray()); } else { string str4 = string.Format(" UPDATE MiddleTable SET MoneyAmount= '{0}' WHERE SerialNumber='{1}'", @decimal, serialNumber); SqlHelper.ExecuteNonQuery(CommandType.Text, str4, null); } } reader.Close(); reader.Dispose(); db2Update(); } catch (Exception exception) { Log4netHelper.Error(exception, "db2error", "db2error"); } }
/// <summary> /// 按GUID 查找主服务 /// </summary> /// <param name="characteristic">GUID 字符串</param> /// <returns></returns> public async Task SelectDeviceService() { Guid guid = new Guid(ServiceGuid); CurrentDevice.GetGattServicesForUuidAsync(guid).Completed = (asyncInfo, asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { try { GattDeviceServicesResult result = asyncInfo.GetResults(); if (result.Services.Count > 0) { CurrentService = result.Services[CHARACTERISTIC_INDEX]; if (CurrentService != null) { asyncLock = true; GetCurrentWriteCharacteristic(); GetCurrentNotifyCharacteristic(); } } } catch (Exception ex) { Log4netHelper.Error(ex); } } }; }
/// <summary> /// byte转为double && IEE754标准 /// </summary> /// <returns></returns> public static bool ToHex() { try { byte[] frame = new byte[4]; double[] double_data_copy = new double[datas.Length / 4]; for (int i = 0, j = 0; j < datas.Length; i++, j += 4) { //将传入的字节数组的每4个字节复制到临时缓冲区 Array.Copy(datas, j, frame, 0, 4); //逆转小端字节序 Array.Reverse(frame); //将临时缓冲区的值转换成整数,并赋给num int num = BitConverter.ToInt32(frame, 0); //调用int转16进制字符串方法 string s = ConvertHelper.ToHexString(num, 8); //调用16进制字符串转浮点数方法 double_data_copy[i] = ConvertHelper.IntStringTodouble(s); } double_data = ConvertHelper.RoundAccuracy(double_data_copy); return(true); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }
public string[] GetNamedOUArray() { string[] TempArray = null; try { XmlDocument doc = new XmlDocument(); doc.Load(LogPath); XmlNodeList nodelist = doc.GetElementsByTagName("NamedOU"); if (nodelist.Count > 0) { TempArray = new string[nodelist.Count]; for (int i = 0; i < nodelist.Count; i++) { TempArray[i] = nodelist[i].Attributes["name"].Value; } } else { Log4netHelper.Error(string.Format(" *********************GetNamedOUArray nodelist count is 0")); } doc.Save(LogPath); } catch (Exception ex) { TempArray = null; Log4netHelper.Error(string.Format(" *********************GetNamedOUArray Exception:{0}", ex.ToString())); } return(TempArray); }
public void Execute(IJobExecutionContext context) { lock (locker) { if (_isRunning) { return; } _isRunning = true; } try { //如果数据库中表数据较多,不要一次性转历史,每次转100条 const int maxCountPerConvert = 20;//每次转历史的最大条数 } catch (Exception ex) { Log4netHelper.Error("执行数据库转历史任务:" + ex); } finally { lock (locker) { _isRunning = false; } } }
public static void SapSmStockImport() { string cmdText = " SELECT * FROM ZJIANWEN_KC WHERE FLAG=0"; string str2 = " INSERT INTO Sap_JWSmStock VALUES(@PrjCode,@Tcode,@Scode,\r\n @Snumber,@Sprice,@InputDate,@Flag )"; try { OleDbDataReader reader = ExecuteReader(CommandType.Text, cmdText, null); while (true) { if (!reader.Read()) { break; } SqlHelper.ExecuteNonQuery(CommandType.Text, str2, new List <SqlParameter> { new SqlParameter("@PrjCode", DBHelper.GetString(reader["PROJNO"])), new SqlParameter("@Tcode", DBHelper.GetString(reader["LGORT"])), new SqlParameter("@Scode", DBHelper.GetString(reader["MATNR"])), new SqlParameter("@Snumber", DBHelper.GetString(reader["MENGE"])), new SqlParameter("@Sprice", DBHelper.GetDecimal(reader["MONEY"])), new SqlParameter("@InputDate", DBHelper.GetDateTimeNullable(reader["F_DATE"])), new SqlParameter("@Flag", DBHelper.GetBool(reader["FLAG"])) }.ToArray()); } reader.Close(); reader.Dispose(); SapUpdate(); } catch (Exception exception) { Log4netHelper.Error(exception, "SapError", "SapError"); } }
public void OnException(ExceptionContext context) { Exception ex = context.Exception; Log4netHelper.Error(ex.Message); //记录错误日志 InsertSysLog(ex.Message); //添加到数据库 context.ExceptionHandled = true; //代表异常已经处理,不会再跳转到开发调试时的异常信息页,可以跳转到我们下面自定义的方法中。若开发过程可以将 该行注释掉,则直接抛出异常调试 //通过HTTP请求头来判断是否为Ajax请求,Ajax请求的request headers里都会有一个key为x-requested-with,值“XMLHttpRequest” var requestData = context.HttpContext.Request.Headers.ContainsKey("x-requested-with"); bool IsAjax = false; if (requestData) { IsAjax = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest" ? true : false; } if (!IsAjax)//不是异步请求则跳转页面,异步请求则返回json { context.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Error", message = WebUtility.HtmlEncode(ex.Message) })); } else { context.Result = new JsonResult(new { Success = false, Code = 500, Message = ex.Message }); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="buffer"></param> public bool Send(byte[] buffer) { if (buffer == null || buffer.Length == 0) { //没有数据发送,默认是发送成功的 return(true); } //如果连接没有建立,新建立连接,防止连接异常的问题。 if (!isRunning) { Start(); } try { //在阻塞情况下,send会返回整数正好等于要发送的数据数据, //If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does not have O_NONBLOCK(非阻塞状态) set, send() shall block until space is available. If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does have O_NONBLOCK set, send() shall fail. retry.Invoke(() => socket.Send(buffer, 0, buffer.Length, SocketFlags.None)); return(true); } catch (Exception ex) { //发送错误,可能是断线 isRunning = false; Log4netHelper.Error(string.Format("发送数据发生错误:{0}", ex)); return(false); } }
/// <summary> /// 处理收到的客户端消息 /// </summary> /// <param name="result"></param> /// <param name="buffer"></param> /// <param name="userWebSocket"></param> /// <param name="wsFactory"></param> /// <returns></returns> public async Task HandleMessage(WebSocketReceiveResult result, byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory) { string msg = Encoding.UTF8.GetString(buffer, 0, result.Count); try { if (msg.Equals("ping")) //心跳监测 { //Log4netHelper.Error(this, "HandleMessage:心跳监测:" + msg); byte[] buffer1 = Encoding.UTF8.GetBytes(msg); await userWebSocket.WebSocket.SendAsync(new ArraySegment <byte>(buffer1, 0, buffer1.Length), WebSocketMessageType.Text, true, CancellationToken.None); } else { //Log4netHelper.Error(this, "HandleMessage:" + msg); //var message = JsonConvert.DeserializeObject<CustomWebSocketMessage>(msg); //if (message.Type == "test") //{ // await BroadcastOthers(buffer, userWebSocket, wsFactory); //} } } catch (Exception ex) { Log4netHelper.Error(this, ex); await userWebSocket.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } }
/// <summary> /// 查找数据库中所有的HZ表记录 /// </summary> /// <param name="_data"></param> /// <returns></returns> public bool FindAllHZ(Data _data) { try { string sql1 = "select gears from info where name = '" + _data.Name + "'"; DataTable dt1 = SQLiteHelper.ExecuteDataTable(sql1, null); if (dt1.Rows.Count != 1) { return(false); } string fetname = dt1.Rows[0].ItemArray[0].ToString(); if (fetname.Equals("")) { return(false); } string sql = @XmlHelper.getValue(_data.Name, "select") + "'" + _data.Name + "'"; string sql2 = string.Format(sql, fetname); DataTable dt = SQLiteHelper.ExecuteDataTable(sql2, null); _data.HZCount = dt.Rows.Count; if (_data.HZCount == 0) { return(false); } _data.GridDataSource = dt; return(true); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }
/// <summary> /// 水印文件覆盖原文件 /// </summary> /// <param name="ouputFilePath">水印文件</param> private void CoverInputFile(string ouputFilePath) { FileInfo info = new FileInfo(ouputFilePath); FileInfo info2 = new FileInfo(this.inputFile); try { if (info.Exists && info2.Exists) { Thread.Sleep(0x7d0); info2.Delete(); info.MoveTo(this.inputFile); } } catch { try { string name = info2.Name; name = name.Substring(0, name.IndexOf('.')) + "(签章)" + info2.Extension; string destFileName = this.inputFile.Substring(0, this.inputFile.IndexOf('/') + 1) + name; info.MoveTo(destFileName); } catch (Exception exception) { Log4netHelper.Error(exception, "pdfMoveDeleteError", ""); } } }
/// <summary> /// 获取表格DVG数据,通过读取原始dat文件 /// </summary> /// <param name="_data"></param> /// <returns></returns> public bool GetDGVData(Data _data) { try { watch1.Start(); List <double[]> dt = DatHelper.ReadDat(_data.Name); watch1.Stop(); //_data.DGVDataSource = dt; if (dt == null || dt.Count == 0) { return(false); } watch2.Start(); if (GEOHelper.normalizationsToFile(dt, _data.Name) == null) { return(false); } watch2.Stop(); Console.WriteLine("DatHelper.ReadDat方法运行时长:" + watch1.Elapsed.TotalMilliseconds); Console.WriteLine("调用geo方法运行时长:" + watch2.Elapsed.TotalMilliseconds); watch1.Reset(); watch2.Reset(); return(true); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }
/// <summary> /// 超时判断 /// </summary> /// <returns></returns> //public async Task<bool> TimeTask() //{ // var task = PrimeTask(); // int timeout = 1000; // if (await Task.WhenAny(task, Task.Delay(timeout)) == task) // { // return true; // } // return false; //} /// <summary> /// 调用Modbus的CRC校验处理 /// </summary> /// <param name="_data"></param> /// <returns></returns> public bool ModbusCRC(Data _data) { try { byte[] bt = _data.SendByList.ToArray(); if (bt == null || bt.Length == 0) { return(false); } if (!Modbus.ReceiveByteArray(bt)) { return(false); } _data.ModbusData = Modbus.double_data; return(true); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }
public static void db2PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] cmdParms) { try { if (conn.State != ConnectionState.Open) { try { conn.Open(); } catch (Exception exception) { Log4netHelper.Error(exception, "db2error", "db2Openerror"); } } cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = cmdType; if (cmdParms != null) { foreach (OleDbParameter parameter in cmdParms) { cmd.Parameters.Add(parameter); } } } catch (Exception exception2) { Log4netHelper.Error(exception2, "db2error", "db2Commanderror"); } }
//测量 private void AddButton(object sender, EventArgs e) { if (bluetooth.CurrentService == null) { _DataForm.ShowToast("提示", "蓝牙未连接,请先连接蓝牙", 1); return; } try { if (!_DataRepository.FindFETByName(_DataForm.InfoName, XmlHelper.getValue("flag"), _DataForm.Gears)) { _DataForm.ShowToast("提示", "当前测线项目不支持该设备,请重新创建测线项目", 3); return; } } catch (Exception ex) { Log4netHelper.Error(ex); return; } _DataRepository.ReadComond(_DataForm.InfoName); //ThreadPool.QueueUserWorkItem((obj) => //{ // for (int i = 0; i < 10; i++) // { // Thread.Sleep(1000); // _DataRepository.ReadComond(_DataForm.InfoName); // } //}); }
public void UpdateTotal2Up(string parentId) { try { new BudModifyService(); new BudModifyTaskService(); while (!string.IsNullOrEmpty(parentId)) { BudTask byId = this.GetById(parentId); if (byId == null) { return; } decimal?nullable = ((IQueryable <decimal?>)(from t in this where t.ParentId == parentId select t.Total2)).Sum(); if (!nullable.HasValue) { nullable = 0M; } byId.Total2 = nullable; base.Update(byId); parentId = byId.ParentId; } } catch (Exception exception) { string title = string.Format("BudTaskService.UpdateTotal2Up({0})", parentId); Log4netHelper.Error(exception, title, "bery"); } }
/// <summary> /// 数据校验入口 /// </summary> /// <param name="buff_copy"></param> /// <returns></returns> public static bool ReceiveByteArray(byte[] buff_copy) { if (buff_copy == null || buff_copy.Length == 0) { Log4netHelper.Error("modbus校验前数据为空"); return(false); } //if (gMBSci.cmd[gMBSci.index].stat != buff_copy[1]) //{ // Log4netHelper.Error("modbus功能码有误"); // return false; //} if (Crc16(buff_copy, buff_copy.Length) != 0) { Log4netHelper.Error("CRC验证错误"); return(false); } //提取数据区的数据,结果数据存储在datas中 || 如果是04,则进一步转为浮点数,结果存储在double_data中 if (!DataFormat(buff_copy)) { return(false); } return(true); }
public void OnException(ExceptionContext context) { if (_hostingEnvironment.IsDevelopment()) { //开发环境 return; } //记录错误日志 Log4netHelper.Error(typeof(HttpGlobalExceptionFilter), context.Exception); // context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; if (context.HttpContext.Request.IsAjax()) { context.Result = new JsonResult(new ResponseModel { RetCode = StatesCode.failure, RetMsg = "服务器出现故障啦,请联系管理员查看错误日志!" }); } else { context.Result = new RedirectResult("/home/error"); } //代表错误已经被处理了 context.ExceptionHandled = true; }
/// <summary> /// 关闭连接 /// </summary> public void Stop() { if (socket == null) { isRunning = false; return; } try { //This ensures that all data is sent and received on the connected socket before it is closed. socket.Shutdown(SocketShutdown.Both); socket.Close(); Log4netHelper.Info(string.Format("关闭{0}:{1}成功", ip, port)); } catch (Exception ex) { socket.Close(); Log4netHelper.Error(string.Format("关闭{0}:{1}时发生异常:{2}。", ip, port, ex)); } finally { socket = null; isRunning = false; } }
public static void ClearTotal2(object o) { Log4netHelper.Error(new Exception("clearTotal2 开始执行"), "clearTotal2", "bery"); BasicConfigService service = new BasicConfigService(); BasicConfig byName = service.GetByName("IsClearTaskTotal2"); if (byName.ParaValue != "1") { try { BudTaskService service2 = new BudTaskService(); BudModifyTaskService source = new BudModifyTaskService(); new PTPrjInfoService(); foreach (BudModifyTask task in source.ToList <BudModifyTask>()) { source.UpdateTotal2(task.ModifyTaskId); } string cmdText = string.Format("\r\n\t\t\t\t\tSELECT TaskId FROM Bud_Task\r\n\t\t\t\t\tWHERE TaskId IN ( SELECT TaskId FROM Bud_TaskResource )\r\n\t\t\t\t", new object[0]); DataTable table = SqlHelper.ExecuteQuery(CommandType.Text, cmdText, new SqlParameter[0]); for (int i = 0; i < table.Rows.Count; i++) { string taskId = table.Rows[i][0].ToString(); service2.UpdateTotal2(taskId); } byName.ParaValue = "1"; service.Update(byName); Log4netHelper.Error(new Exception("clearTotal2 执行成功"), "clearTotal2", "bery"); } catch (Exception exception) { Log4netHelper.Error(exception, "clearTotal2", "bery"); } } }
public List <T> GetStringListKey <T>(string key) { List <T> addrs = new List <T>(); try { var redisResult = CacheRedis.ScriptEvaluate(LuaScript.Prepare( //Redis的keys模糊查询: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = key }); if (!redisResult.IsNull) { var values = CacheRedis.StringGet((RedisKey[])redisResult); for (var i = 0; i < values.Length; i++) { addrs.Add(JsonConvert.DeserializeObject <T>(values[i])); } } } catch (Exception er) { Log4netHelper.Error(this, er); } return(addrs); }
public static ICollection <PSObject> ExecuteCmdlet(string cmdlet) { if (cmdlet == null) { throw new ArgumentNullException("cmdlet"); } if (cmdlet.Length == 0) { throw new ArgumentException("cmdlet length is zero", "cmdlet"); } ICollection <PSObject> is2 = null; Pipeline pipeline = null; List <object> errorList = new List <object>(); try { lock (sync) { if (_runspace.RunspaceStateInfo.State == RunspaceState.Broken) { _runspace.Close(); ReOpen(); } else if (_runspace.RunspaceStateInfo.State == RunspaceState.Closed) { ReOpen(); } SubmitSecurity subSecurity = new SubmitSecurity(); if (subSecurity.impersonateValidUser(DomainAdmin, Domain, DomainAdminPass)) { pipeline = _runspace.CreatePipeline(); using (Pipeline pipeline2 = pipeline) { pipeline.Commands.AddScript(cmdlet); is2 = pipeline.Invoke(); if (pipeline.Error != null && pipeline.Error.Count > 0) { foreach (object item1 in pipeline.Error.ReadToEnd()) { errorList.Add(item1); string errorMessage = string.Format("Invoke error: {0}", item1); Log4netHelper.Error(errorMessage); } } } } } } finally { pipeline = null; } return(is2); }
public bool WorkerOperation(UserSensitiveMailQueueInfo info) { ErrorCodeInfo error = new ErrorCodeInfo(); string message = string.Empty; string resultmessage = string.Empty; Guid transactionid = Guid.NewGuid(); string paramstr = string.Empty; paramstr += $"SensitiveID:{info.ID}"; paramstr += $"||Keywords:{info.Keywords}"; paramstr += $"||StartTime:{info.StartTime}"; paramstr += $"||EndTime:{info.EndTime}"; paramstr += $"||UserID:{info.UserID}"; bool bResult = true; try { do { Log4netHelper.Info($"RemoveSensitiveMail Begin: {paramstr}"); CommonProvider commonProvider = new CommonProvider(); DirectoryEntry userEntry = new DirectoryEntry(); SensitiveMailDBProvider provider = new SensitiveMailDBProvider(); if (!commonProvider.GetADEntryByGuid(info.UserID, out userEntry, out message)) { Log4netHelper.Error($"RemoveSensitiveMail GetADEntryByGuid ID:{info.UserID}, Error:{message}"); info.Status = SensitiveMailStatus.Failed; resultmessage = "用户不存在。"; provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error); bResult = false; break; } string userMail = userEntry.Properties["mail"].Value == null ? "" : Convert.ToString(userEntry.Properties["mail"].Value); ADManagerWebService.ManagerWebService webService = new ADManagerWebService.ManagerWebService(); webService.Timeout = -1; if (!webService.RemoveSensitiveMail(transactionid, userMail, info.Keywords, info.StartTime, info.EndTime, out resultmessage, out message)) { info.Status = SensitiveMailStatus.Failed; provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error); Log4netHelper.Error($"RemoveSensitiveMail ID:{info.ID}, Error:{message}"); bResult = false; break; } //记录执行日志 info.Status = SensitiveMailStatus.Success; provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error); Log4netHelper.Info($"RemoveSensitiveMail End: {paramstr}"); } while (false); } catch (Exception ex) { Log4netHelper.Error("RemoveSensitiveMail异常", paramstr, ex.ToString(), transactionid); bResult = false; } return(bResult); }
public CXmlOUList(string xmlFileName) { if (xmlFileName.Length > 0) { XmlTargets = xmlFileName; } m_document = new XmlDocument(); m_document.Load(LogPath); Log4netHelper.Error(" *********************LogPath " + LogPath); _enritys = new List <OUSEntity>(); }
public void logSend(string mlog) { Log4netHelper.Error(this, mlog); LogModel lg = new LogModel(); lg.SystemTime = DateTools.TimeToDouble(DateTime.Now); lg.SatelliteTime = 0; lg.Source = "webSystem"; lg.Message = mlog; msgSend.send <LogModel>("Log", lg); }
public void Save(object sender, EventArgs e) { try { SendKeys.SendWait("{ENTER}"); for (int i = 0; i < dataGridViewX1.Rows.Count; i++) { if (!string.IsNullOrEmpty(dataGridViewX1.Rows[i].Cells[1].ErrorText)) { UIHelper.ToastNotify(false, "保存失败,正式生产表中存在不合理数据,请重新检查!", tabControl1); Log4netHelper.Error(this.GetType(), string.Format("正式生产表中存在不合理数据,请重新检查!第{0}行,第{1}列,原因是:{2}", i, 1, dataGridViewX1.Rows[i].Cells[1].ErrorText)); return; } } //获取盒子名称; Boxtype_str = GetBoxtypeName(); if (Boxtype_str == "NULL") { BoxType_TextBox.Focus(); return; } //先判断是否已存在 DataTable sql_dt = sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("select sgboxtype from {0} where sgboxtype='{1}'", Constant.Boxtype_sqlname, Boxtype_str), null); if (sql_dt.Rows.Count > 0 && !submit_flag) { UIHelper.ToastNotify(false, "该型号已存在,请不要重复创建!--" + Boxtype_str, tabControl1); return; } DataTable formal_dt = ((DataTable)dataGridViewX1.DataSource).Copy(); StringBuilder Formal_strconn = DgdDealHelper.GetCombineInfo(formal_dt); if (submit_flag) { sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update {0} set sgboxinfo='{1}',sgboxinfo_test='{2}' where sgboxtype='{3}'", Constant.Boxtype_sqlname, Formal_strconn, Formal_strconn, Boxtype_str), null); DgdDealHelper.Deal_DifDgdValue(this.Text, NotModify_dt1, dataGridViewX1, "正式表"); UIHelper.ToastNotify(true, "表数据修改保存成功!", tabControl1); } else { sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (sgboxtype,sgboxinfo,sgboxinfo_test)values('{1}','{2}','{3}')", Constant.Boxtype_sqlname, Boxtype_str, Formal_strconn, Formal_strconn), null); SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}')", Constant.RecordLog_sqlname, Boxtype_str, Constant.CurUserName(), DateTime.Now, "创建Boxtype"), null); //创建节点 CreateTypeNode(parent_str, Boxtype_str); UIHelper.ToastNotify(true, "表数据创建成功!", tabControl1); Log4netHelper.Info(this.GetType(), Boxtype_str + "表数据创建成功!"); } NotModify_dt1 = formal_dt; submit_flag = true; CloseCreatForm(this.Text); } catch (Exception ex) { MessageBox.Show("保存时发生异常:" + ex.Message); } }
/// <summary> /// 提取modbus数据区 /// </summary> /// <param name="buff_copy"></param> /// <returns></returns> public static bool DataFormat(byte[] buff_copy) { try { rBuff = new byte[buff_copy.Length]; Array.Copy(buff_copy, rBuff, buff_copy.Length); //0x10功能 && 暂保留 if (rBuff[1] == MB_WRITE_MULTIPLE_REGS) { return(false); } //0x06功能 && 暂保留 if (rBuff[1] == MB_WRITE_SINGLE_REG) { return(false); } //0x03功能 && 定时电量查询服务 if (rBuff[1] == MB_READ_HOLD_REG) { datas = new byte[buff_copy[2]]; Array.Copy(buff_copy, 3, datas, 0, buff_copy[2]); return(true); } //0x04功能 && 采集数据服务 if (rBuff[1] == MB_READ_INPUT_REG) { byte[] b = new byte[4] { buff_copy[3], buff_copy[2], (byte)0, (byte)0 }; int num = BitConverter.ToInt32(b, 0); datas = new byte[num]; Array.Copy(buff_copy, 4, datas, 0, num); if (!ToHex()) { return(false); } return(true); } Log4netHelper.Error("未知功能码:" + rBuff[1]); return(false); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }
public override void OnException(HttpActionExecutedContext context) { var exception = context.Exception; while (exception.InnerException != null) { exception = exception.InnerException; } // 异常过滤 switch (exception) { default: break; case AppException appException: case TaskCanceledException taskCanceledException: case OperationCanceledException operationCanceledException: context.Response = context.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, exception.Message); Log4netHelper.Info(exception.Message, exception); return; } var parameters = new Dictionary <string, object>(); // 添加路由参数 if (context.ActionContext.RequestContext.RouteData.Values.ContainsKey("id")) { parameters.Add("id", context.ActionContext.RequestContext.RouteData.Values["id"]); } var actionArguments = context.ActionContext.ActionArguments.Select(m => new KeyValuePair <string, string>(m.Key, JsonConvert.SerializeObject(m.Value))); // 添加请求参数 var request = HttpContext.Current?.Request; var queryParams = request?.QueryString.Count > 0 ? request?.QueryString : request?.Form; foreach (var key in queryParams?.AllKeys ?? new string[0]) { parameters.Add(key, queryParams[key]); } // 将参数加入到异常数据中 foreach (var item in parameters) { exception.Data.Add(item.Key, item.Value); } // 记录日志 Log4netHelper.Error("Global", exception); }
/// <summary> /// 记录异常记录 /// </summary> private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { try { string exStr = string.Format("{0}:{1}", sender.ToString(), e.Exception.Message + e.Exception.StackTrace); Log4netHelper.Error(exStr); MessageBox.Show(exStr); } catch (System.Exception) { } }
/// <summary> /// 删除原始dat文件最后一条测点 /// </summary> /// <param name="Lastid"></param> /// <returns></returns> public bool DeleteDat(string FileName) { try { return(DatHelper.DeleteDat(FileName)); } catch (Exception ex) { Log4netHelper.Error(ex); return(false); } }