/// <summary> /// 获取参数坐标 /// </summary> /// <param name="templateId">获取模板参数</param> /// <returns>模板参数列表</returns> private List <ExpressParamViewModel> GetExpressParams(string templateId) { var exParams = new List <ExpressParamViewModel>(); if (cache.Contains(templateId)) { exParams = cache.Get(templateId) as List <ExpressParamViewModel>; } else { var cc = new ConditionCollection(); cc.Add(new Condition("template_id", templateId)); var list = this.GetRepository <McpTemplateParamInfo>().ListModel(cc); if (list != null) { foreach (var param in list) { exParams.Add(new ExpressParamViewModel() { param_code = TryConvertUtil.ToString(param.ParamCode), loc_x = TryConvertUtil.ToDecimal(param.LocX), loc_y = TryConvertUtil.ToDecimal(param.LocY), param_type = param.ParamType, is_need = TryConvertUtil.ToBool(param.IsNeed) }); } } cache.Add(templateId, exParams, DateTimeOffset.Now.AddHours(24)); } return(exParams); }
/// <summary> /// 创建链接及注册 /// </summary> private void TcpConnect() { try { lock (syncLock) { //1.断开现有TCP服务 DisTcpConnect(); //2.设定服务器IP地址 string tcpip = ConfigUtil.GetConfig("TCPServerIP"); int port = TryConvertUtil.ToInt(ConfigUtil.GetConfig("TCPServerPort"), 0); if (port <= 0) { LogUtil.Info("TCP服务端口为空!"); throw new MessageException("TCP服务端口不能为空!"); } else { IPAddress ip = IPAddress.Parse(tcpip); _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _clientSocket.Connect(new IPEndPoint(ip, port)); //配置服务器IP与端口 LogUtil.Info("连接TCP服务器成功!"); } //开始心跳检测 ChangeTimer(true); } } catch (Exception ex) { LogUtil.Error(string.Format("连接TCP服务器失败,参考信息:{0}!", ex)); } }
/// <summary> /// 校验终端是否存在于黑名单中 /// </summary> /// <param name="terminalCode"></param> /// <returns></returns> private bool IsExistVerifycodeBlackList(string appSign, string terminalCode) { string sql = "SELECT COUNT(black_id) FROM mcp_sys_blacklist WHERE app_sign=$app_sign$ AND terminal_code=$terminal_code$ AND lock_expire_date>CURRENT_TIMESTAMP() LIMIT 1;"; ParameterCollection pc = new ParameterCollection(); pc.Add("app_sign", appSign); pc.Add("terminal_code", terminalCode); object exist = DbUtil.DataManager.Current.IData.ExecuteScalar(sql, pc); return(TryConvertUtil.ToInt(exist, 0) > 0); }
public void CheckSocketAlive(object sender, ElapsedEventArgs e) { //N秒无心跳断开连接 var connections = GetConnetionList(); int timeOut = TryConvertUtil.ToInt(ConfigUtil.GetConfig("TcpDisconnectTime"), 0); if (connections != null && connections.Length > 0) { connections.Where(s => s.Active == false || (DateTime.Now - s.LatestActiveTime).TotalSeconds > timeOut) .ToList().ForEach(ss => ss.BeginDisconnect()); } }
/// <summary> /// 获取访问令牌 /// </summary> /// <param name="app">应用参数</param> /// <returns>访问令牌</returns> public object GetAccessToken(AppViewModel app) { try { //1.校验应用信息 CheckApp(app.app_id, app.app_key); //2.获取访问令牌 var tokenDic = new Dictionary <string, object>(); ConditionCollection cc = new ConditionCollection(); cc.Add(new Condition("app_id", TryConvertUtil.ToString(app.app_id))); cc.Add(new Condition("app_key", TryConvertUtil.ToString(app.app_key))); var accToken = this.GetRepository <McpAppTokenInfo>().GetModel(cc); var dbNow = CommonUtil.GetDBDateTime(); if (accToken != null) { //更新token及有效期 tokenDic = UpdateAccessToken(app); #region 原版日期判断代码 2018-3-28 13:52:34 out //if (accToken.CreatedOn.AddSeconds(accToken.ExpiresIn).AddSeconds(60) <= dbNow) //{ // //更新token及有效期 // tokenDic = UpdateAccessToken(app); //} //else //{ // //有效期内直接返回 // TimeSpan span = dbNow - accToken.CreatedOn; // double newExpiresIn = accToken.ExpiresIn - span.TotalSeconds; // tokenDic.Add("access_token", TryConvertUtil.ToString(accToken.AccessToken)); // tokenDic.Add("expires_in", newExpiresIn); //} #endregion } else { //创建新token及有效期 tokenDic = CreateAccessToken(app); } return(tokenDic); } catch (Exception ex) { throw new MessageException(ex.Message); } }
/// <summary> /// 获取201命令任务 /// </summary> /// <param name="orderId"></param> /// <returns></returns> public McpCmdOrderInfo GetCmdOrder(string orderId) { try { ConditionCollection cc = new ConditionCollection(); cc.Add(new Condition("order_id", TryConvertUtil.ToString(orderId))); return(this.GetRepository <McpCmdOrderInfo>().GetModel(cc)); } catch (Exception ex) { LogUtil.Info(string.Format("获取命令订单错误,参考信息:{0},order_id:{1}", ex.Message, orderId)); LogUtil.Error(string.Format($"获取命令订单错误,order_id:{orderId}"), ex); return(null); } }
/// <summary> /// 获取AppId /// </summary> /// <param name="accessToken">访问令牌</param> /// <returns></returns> public string GetAppIdByAccessToken(string accessToken) { var cc = new ConditionCollection(); cc.Add(new Condition("access_token", TryConvertUtil.ToString(accessToken))); var token = this.GetRepository <McpAppTokenInfo>().GetModel(cc); if (token != null) { return(token.CreatedOn.AddSeconds(token.ExpiresIn) > CommonUtil.GetDBDateTime() ? token.AppId : string.Empty); } else { return(string.Empty); } }
/// <summary> /// 校验统计年月字符传 /// </summary> /// <param name="month">统计年月</param> public void CheckMonthIsValid(string month) { month = TryConvertUtil.ToString(month); CheckMonth(month); try { string yy = month.Substring(0, 4); string mm = month.Substring(4, 2); DateTime dt = new DateTime(TryConvertUtil.ToInt(yy), TryConvertUtil.ToInt(mm), 1); } catch { throw new MessageException("参数错误!"); } }
public static TResult ToModel <TResult>(this DataRow row) where TResult : class, new() { if (row == null) { return(null); } DataTable dt = row.Table; //创建一个属性的列表 List <PropertyInfo> prlist = new List <PropertyInfo>(); //获取TResult的类型实例 反射的入口 Type t = typeof(TResult); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach <PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) { prlist.Add(p); } }); //创建返回的集合 List <TResult> oblist = new List <TResult>(); //创建TResult的实例 TResult ob = new TResult(); //找到对应的数据 并赋值 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) { Type dataType = row[p.Name].GetType(); switch (dataType.Name) { case "MySqlDateTime": p.SetValue(ob, TryConvertUtil.ToDateTime(row[p.Name]), null); break; default: p.SetValue(ob, row[p.Name], null); break; } } }); //放入到返回的集合中. return(ob); }
/// <summary> /// 读缓存 /// </summary> /// <param name="did"></param> /// <returns></returns> public int GetCache(string key) { var scode = 0; try { if (cache.Contains(key)) { scode = TryConvertUtil.ToInt(cache.Get(key)); } } catch (Exception ex) { LogUtil.Info(string.Format("读取key:{0}value发生异常,参考信息:{1}", key, ex.Message)); } return(scode); }
/// <summary> /// 校验访问令牌 /// </summary> /// <param name="appId">应用ID</param> /// <param name="accessToken">访问令牌</param> /// <returns>是否合法</returns> public bool CheckAccessToken(string appId, string accessToken) { ConditionCollection c1 = new ConditionCollection(); c1.Add(new Condition("app_id", TryConvertUtil.ToString(appId))); c1.Add(new Condition("access_token", TryConvertUtil.ToString(accessToken))); var token = this.GetRepository <McpAppTokenInfo>().GetModel(c1); if (token != null) { return(token.CreatedOn.AddSeconds(token.ExpiresIn) > CommonUtil.GetDBDateTime()); } else { return(false); } }
/// <summary> /// 更新访问令牌 /// </summary> /// <param name="app">应用参数</param> /// <returns>访问令牌</returns> private Dictionary <string, object> UpdateAccessToken(AppViewModel app) { var tokenDic = new Dictionary <string, object>(); var token = new McpAppTokenInfo() { AppId = app.app_id, AppKey = app.app_key, AccessToken = CommonUtil.GetGuidNoSeparator(), ExpiresIn = ConfigUtil.TokenExpireIn, CreatedOn = CommonUtil.GetDBDateTime(), }; this.GetRepository <McpAppTokenInfo>().Update(token, "access_token,expires_in,created_on"); tokenDic.Add("access_token", TryConvertUtil.ToString(token.AccessToken)); tokenDic.Add("expires_in", token.ExpiresIn); return(tokenDic); }
/// <summary> /// 获取用户openID /// </summary> /// <param name="code"></param> /// <returns></returns> public static string GetWechatOpenId(string code) { string openId = String.Empty; string wechatAppId = ConfigUtil.WechatAppIdForIot; string wechatAppSecret = ConfigUtil.WechatAppSecretForIot; string url = String.Format(WeChatConsts.WECHAT_GET_OPENID, wechatAppId, wechatAppSecret, code); string resultText = NetUtil.WechatSendPostRequest(url, string.Empty); LogUtil.Debug(string.Format("GetWechatOpenId: code: {0}, res: {1}", code, resultText)); Dictionary <string, object> dicWechat = JsonUtil.Deserialize <Dictionary <string, object> >(resultText); if (dicWechat.ContainsKey("openid")) { openId = TryConvertUtil.ToString(dicWechat["openid"], string.Empty); } return(openId); }
/// <summary> /// 校验统计月 /// </summary> /// <param name="month">统计月</param> public DateTime GetStatisMonth(string month) { DateTime statisDate = DateTime.MaxValue; CheckMonth(month); try { int yy = TryConvertUtil.ToInt(month.Substring(0, 4), DateTime.MaxValue.Year); int mm = TryConvertUtil.ToInt(month.Substring(4, 2), DateTime.MaxValue.Month); statisDate = new DateTime(yy, mm, 1); } catch (Exception ex) { LogUtil.Warn(string.Format("统计月份参数错误,参考信息:{0}。", ex.Message)); throw new MessageException(string.Format("统计月份参数错误!")); } return(statisDate); }
/// <summary> /// 获取设备列表【授权或开通WiFi】 /// </summary> /// <returns></returns> public object GetDevices(PageViewModel pageModel, out int pageCount) { var list = GetDeviceList(pageModel); int totalCount = this.GetRepository <McpEquipmentInfo>().Count(); int pageSize = pageModel.PageSize > 0 ? pageModel.PageSize : 10; pageCount = (int)Math.Ceiling(TryConvertUtil.ToDecimal(totalCount) / pageSize); return(from o in list select new { EquId = o.EquipmentId, EquCode = o.EquipmentCode, SnCode = o.CheckCode, DeviceId = o.DeviceId, IsAuth = o.IsAuth, IsOpenWifi = o.IsOpenWifi }); }
/// <summary> /// 发送短信 /// </summary> /// <param name="appSign"></param> /// <param name="mobile"></param> /// <param name="content"></param> /// <param name="smsType"></param> /// <returns></returns> public void SendSmsMessage(string appSign, string mobile, Dictionary <string, object> parms, string content, SMSType smsType, SmsFuncType tempType) { // 参数检查 if (string.IsNullOrWhiteSpace(appSign)) { throw new MessageException("应用标识不能为空!"); } if (string.IsNullOrWhiteSpace(mobile)) { throw new MessageException("手机号码不能为空!"); } if (parms.Count <= 0) { throw new MessageException("短信内容参数不能为空!"); } if (string.IsNullOrWhiteSpace(content)) { throw new MessageException("短信内容不能为空!"); } if (!RegexUtil.IsMobile(mobile)) { throw new MessageException(string.Format("手机号码:{0},格式不正确。" + mobile)); } var smsId = CreateSmsRecord(appSign, mobile, content, smsType); switch (smsType) { case SMSType.Bind: case SMSType.UnBind: case SMSType.GetPwd: case SMSType.ValidateCode: SmsUtil.SendValidCode(mobile, parms["code"].ToString(), TryConvertUtil.ToDecimal(parms["code_expire"], 2), tempType); break; default: break; } }
/// <summary> /// 校验应用 /// </summary> /// <param name="appId">应用ID</param> /// <param name="appKey">应用Key</param> /// <returns>是否有效</returns> public bool CheckApp(string appId, string appKey = "") { bool isOk = false; ConditionCollection c1 = new ConditionCollection(); c1.Add(new Condition("app_id", TryConvertUtil.ToString(appId))); if (!string.IsNullOrWhiteSpace(appKey)) { c1.Add(new Condition("app_key", TryConvertUtil.ToString(appKey))); } var application = this.GetRepository <McpApplicationInfo>().GetModel(c1); if (application != null) { switch (application.StatusCode) { case (int)StatusCodeType.New: throw new MessageException(string.Format("应用处于{0}状态!", StatusCodeType.New.GetRemark())); case (int)StatusCodeType.Disabled: throw new MessageException(string.Format("应用处于{0}状态!", StatusCodeType.Disabled.GetRemark())); case (int)StatusCodeType.Deleted: throw new MessageException(string.Format("应用处于{0}状态!", StatusCodeType.Deleted.GetRemark())); default: break; } ; isOk = true; } else { throw new MessageException("无效应用,app_id或app_key参数错误!"); } return(isOk); }
/// <summary> /// 检查版本信息 /// </summary> /// <param name="verModel">版本信息参数</param> /// <returns>版本信息结果</returns> public object CheckVersion(VerViewModel verModel) { //校验设备表示 bool isExist = SingleInstance <PrinterService> .Instance.CheckEquipmentIsExists(verModel.Mac); if (!isExist) { LogUtil.Info($"设备不存在-{JsonUtil.Serialize(verModel)}"); throw new MessageException("设备不存在!"); } //更改设备对应版本号 bool result = SingleInstance <PrinterService> .Instance.UpdatePrintVersion(verModel); if (!result) { throw new MessageException($"更新打印机{verModel.Mac}版本号失败,请重试"); } //获取版本 Dictionary <string, object> verDic = new Dictionary <string, object>(); ConditionCollection cc = new ConditionCollection(); cc.Add(new Condition("objec_type", TryConvertUtil.ToString(verModel.Type))); cc.Add(new Condition("status_code", StatusCodeType.Valid.GetHashCode())); int isNeed = 0; string newVer = string.Empty; string filePath = string.Empty; var lastVer = this.GetRepository <McpSysVersionInfo>().GetModel(cc); if (lastVer != null) { var isUpdate = false; var serVer = 0; var curVer = 0; var serVers = lastVer.ObjectVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); var curVers = verModel.Ver.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); var maxLength = Math.Max(serVers.Length, curVers.Length); for (var i = 0; i < maxLength; i++) { serVer = i < serVers.Length ? TryConvertUtil.ToInt(serVers[i]) : 0; curVer = i < curVers.Length ? TryConvertUtil.ToInt(curVers[i]) : 0; if (serVer != curVer) { isUpdate = serVer > curVer; break; } else { continue; } } if (isUpdate) { isNeed = lastVer.IsForce > 0 ? 2 : 1; newVer = lastVer.ObjectVersion; filePath = lastVer.VersionFile; } } verDic.Add("IsNeedUpdate", isNeed); verDic.Add("NewVer", newVer); verDic.Add("UpdateFilePath", filePath); LogUtil.Info(string.Format("设备:{0},当前版本:{1},获取新版本...", verModel.Mac, verModel.Ver)); return(verDic); }
/// <summary> /// 生成单据编号 /// </summary> /// <returns>单据编号</returns> private string GetNewBillCode() { int maxNum = 99999; ParameterCollection pc = new ParameterCollection(); string strCondition = OtherCondition; var newCode = string.Empty; var lastCode = string.Empty; var querySql = string.Format("SELECT `{0}` FROM {1} {2} ORDER BY `{0}` DESC LIMIT 0,1", CodeField, TableName, strCondition); lastCode = TryConvertUtil.ToString(DbUtil.DataManager.DataManagerMcp.IData.ExecuteScalar(querySql), string.Empty); var lastNum = -1; var prefixLength = 0; var billSerialCode = string.Empty; var day = CommonUtil.GetDBDateTime().Date.ToString("yyMMdd"); if (ConfigUtil.IsTestModel) { day = CommonUtil.GetDBDateTime().Date.AddYears(-10).ToString("yyMMdd");//测试环境使用 querySql = string.Format("SELECT `{0}` FROM {1} WHERE LEFT({0},{3})='{2}' ORDER BY `{0}` DESC LIMIT 0,1", CodeField, TableName, Prefix + day, Prefix.Length + day.Length); lastCode = TryConvertUtil.ToString(DbUtil.DataManager.DataManagerMcp.IData.ExecuteScalar(querySql), string.Empty); } if (lastCode != null && !string.IsNullOrWhiteSpace(lastCode.ToString())) { if (!string.IsNullOrWhiteSpace(Prefix)) { //单据号类似: T2013041100001 billSerialCode = lastCode.ToString().TrimStart(Prefix.ToCharArray()); prefixLength = Prefix.Length; } else { //单据号类似: 130411000001 billSerialCode = lastCode; } var dateLen = 6; //日期长度 if (billSerialCode.Length == dateLen + SerialLength) { //比较日期 var y = TryConvertUtil.ToInt(lastCode.Substring(prefixLength + 0, 2), 10); if (ConfigUtil.IsTestModel) { var temp = TryConvertUtil.ToInt(lastCode.Substring(prefixLength + 0, 2), 10); y = temp > 10 ? temp - 5 : temp;//测试环境使用 } var m = TryConvertUtil.ToInt(lastCode.Substring(prefixLength + 2, 2), 1); var d = TryConvertUtil.ToInt(lastCode.Substring(prefixLength + 4, 2), 1); var n = billSerialCode.Substring(6); //日期相等 if (day == (new DateTime(y, m, d)).ToString("yyMMdd")) { lastNum = TryConvertUtil.ToInt(n.TrimStart('0'), 1); } } } if (lastNum == -1) { lastNum = 0; } lastNum += 1; if (lastNum > maxNum) { throw new BusinessException("当日数据异常"); } newCode = string.Format("{0}{1}{2}", !string.IsNullOrWhiteSpace(Prefix) ? string.Format("{0}", Prefix) : string.Empty, day, lastNum.ToString().PadLeft(SerialLength, '0')); return(newCode); }
public static List <TResult> ToList <TResult>(this DataTable dt) where TResult : class, new() { if (dt == null) { return(null); } //创建一个属性的列表 List <PropertyInfo> prlist = new List <PropertyInfo>(); //获取TResult的类型实例 反射的入口 Type t = typeof(TResult); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach <PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) { prlist.Add(p); } }); //创建返回的集合 List <TResult> oblist = new List <TResult>(); foreach (DataRow row in dt.Rows) { //创建TResult的实例 TResult ob = new TResult(); //找到对应的数据 并赋值 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) { Type dataType = row[p.Name].GetType(); switch (dataType.Name) { case "MySqlDateTime": p.SetValue(ob, TryConvertUtil.ToDateTime(row[p.Name]), null); break; case "Int64": case "Int32": { if (p.PropertyType == typeof(bool)) { p.SetValue(ob, TryConvertUtil.ToInt(row[p.Name]) == 1, null); } else { p.SetValue(ob, TryConvertUtil.ToInt(row[p.Name]), null); } break; } default: p.SetValue(ob, row[p.Name], null); break; } } }); //放入到返回的集合中. oblist.Add(ob); } return(oblist); }