using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Newtonsoft.Json; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data; using System.Data.Sql; using Rdream.Core.Model; using System.Text.RegularExpressions; using System.Runtime.Serialization.Formatters.Binary; using System.Net.Sockets; using System.Collections; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; namespace Rdream.Core.DataHandler { public class SendMsgByAccessControlRecord { #region 配置 Database da = DatabaseFactory.CreateDatabase("ConnectionString"); //人脸识别系统数据源 //主服务URL public static string mainServiceUrl = System.Configuration.ConfigurationManager.AppSettings["mainServiceUrl"]; //学生门禁记录推送企业微信URL public static string _sendMsgByAccessControlRecordUrl = System.Configuration.ConfigurationManager.AppSettings["sendMsgByAccessControlRecordUrl"]; string sendMsgByAccessControlRecordUrl = mainServiceUrl + _sendMsgByAccessControlRecordUrl; //检查服务端门禁人脸图片文件前是否存在URL public static string _checkDoorImageUrl = System.Configuration.ConfigurationManager.AppSettings["checkDoorImageUrl"]; string checkDoorImageUrl = mainServiceUrl + _checkDoorImageUrl; //上传门禁系统人脸图片URL public static string _uploadDoorImageUrl = System.Configuration.ConfigurationManager.AppSettings["uploadDoorImageUrl"]; string uploadDoorImageUrl = mainServiceUrl + _uploadDoorImageUrl; public static string corpId = System.Configuration.ConfigurationManager.AppSettings["CorpId"]; //获取近5秒的门禁学生进出记录,注意该值必须大于轮循休眠时间 public static string seconds = System.Configuration.ConfigurationManager.AppSettings["seconds"]; //延时10秒提交数据 public static string _timeDelay = System.Configuration.ConfigurationManager.AppSettings["timeDelay"]; //延时10秒提交数据。 int timeDelay = (_timeDelay == null || _timeDelay == "") ? 0 : int.Parse(_timeDelay); //两次门禁考勤记录间相同方向在60秒(1分钟)内,不推送微信;为0时都推送。 public static string _twoRecordSameTimes = System.Configuration.ConfigurationManager.AppSettings["twoRecordSameTimes"]; //两次门禁考勤记录间相反方向在60秒(1分钟)内,不推送微信;为0时都推送。 public static string _twoRecordContraryTimes = System.Configuration.ConfigurationManager.AppSettings["twoRecordContraryTimes"]; //两次门禁考勤记录间在60秒(1分钟)内,不推送短信;为0时都推送。 public static string _twoRecordSMSTimes = System.Configuration.ConfigurationManager.AppSettings["twoRecordSMSTimes"]; //请假签到有效时间内1800秒(30分钟) public static string _validTimeLeave = System.Configuration.ConfigurationManager.AppSettings["validTimeLeave"]; //人脸识别照片路径 public static string frpicPath = System.Configuration.ConfigurationManager.AppSettings["frpicPath"]; //刷卡抓拍路径 public static string doorPicPath = System.Configuration.ConfigurationManager.AppSettings["doorPicPath"]; //温度控制不推送消息,由于门禁配置大于等于这个温度不开门。 public static string _temperature = System.Configuration.ConfigurationManager.AppSettings["_temperature"]; // public static string extern_student = System.Configuration.ConfigurationManager.AppSettings["extern_student"]; // public static string boarder_student = System.Configuration.ConfigurationManager.AppSettings["boarder_student"]; // // public static string in_extern_monday = System.Configuration.ConfigurationManager.AppSettings["in_extern_monday"]; public static string in_extern_tuesday = System.Configuration.ConfigurationManager.AppSettings["in_extern_tuesday"]; public static string in_extern_wednesday = System.Configuration.ConfigurationManager.AppSettings["in_extern_wednesday"]; public static string in_extern_thursday = System.Configuration.ConfigurationManager.AppSettings["in_extern_thursday"]; public static string in_extern_friday = System.Configuration.ConfigurationManager.AppSettings["in_extern_friday"]; public static string in_extern_saturday = System.Configuration.ConfigurationManager.AppSettings["in_extern_saturday"]; public static string in_extern_sunday = System.Configuration.ConfigurationManager.AppSettings["in_extern_sunday"]; // public static string out_extern_monday = System.Configuration.ConfigurationManager.AppSettings["out_extern_monday"]; public static string out_extern_tuesday = System.Configuration.ConfigurationManager.AppSettings["out_extern_tuesday"]; public static string out_extern_wednesday = System.Configuration.ConfigurationManager.AppSettings["out_extern_wednesday"]; public static string out_extern_thursday = System.Configuration.ConfigurationManager.AppSettings["out_extern_thursday"]; public static string out_extern_friday = System.Configuration.ConfigurationManager.AppSettings["out_extern_friday"]; public static string out_extern_saturday = System.Configuration.ConfigurationManager.AppSettings["out_extern_saturday"]; public static string out_extern_sunday = System.Configuration.ConfigurationManager.AppSettings["out_extern_sunday"]; // public static string in_boarder_monday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_monday"]; public static string in_boarder_tuesday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_tuesday"]; public static string in_boarder_wednesday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_wednesday"]; public static string in_boarder_thursday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_thursday"]; public static string in_boarder_friday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_friday"]; public static string in_boarder_saturday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_saturday"]; public static string in_boarder_sunday = System.Configuration.ConfigurationManager.AppSettings["in_boarder_sunday"]; // public static string out_boarder_monday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_monday"]; public static string out_boarder_tuesday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_tuesday"]; public static string out_boarder_wednesday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_wednesday"]; public static string out_boarder_thursday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_thursday"]; public static string out_boarder_friday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_friday"]; public static string out_boarder_saturday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_saturday"]; public static string out_boarder_sunday = System.Configuration.ConfigurationManager.AppSettings["out_boarder_sunday"]; //时间段及屏蔽机号 public static string[] shieldDoor = System.Configuration.ConfigurationManager.AppSettings["shieldDoor"].Split(','); public static string swichTime = System.Configuration.ConfigurationManager.AppSettings["swichTime"]; //人脸图片第二路径 public static string[] FacePathDoor = System.Configuration.ConfigurationManager.AppSettings["FacePathDoor"].Split(','); public static string FacePath = System.Configuration.ConfigurationManager.AppSettings["FacePath"]; //SQL语句 public static string SQL_One = System.Configuration.ConfigurationManager.AppSettings["SQL_One"]; public static string SQL_Two = System.Configuration.ConfigurationManager.AppSettings["SQL_Two"]; public static string SQL_Three = System.Configuration.ConfigurationManager.AppSettings["SQL_Three"]; public static string SQL_Four = System.Configuration.ConfigurationManager.AppSettings["SQL_Four"]; public static string SQL_Five = System.Configuration.ConfigurationManager.AppSettings["SQL_Five"]; public static string SQL_IF_One = System.Configuration.ConfigurationManager.AppSettings["SQL_IF_One"]; public static string SQL_IF_One_a = System.Configuration.ConfigurationManager.AppSettings["SQL_IF_One_a"]; public static string SQL_IF_One_b = System.Configuration.ConfigurationManager.AppSettings["SQL_IF_One_b"]; public static string SQL_Six = System.Configuration.ConfigurationManager.AppSettings["SQL_Six"]; public static string SQL_Seven = System.Configuration.ConfigurationManager.AppSettings["SQL_Seven"]; public static string SQL_Eight = System.Configuration.ConfigurationManager.AppSettings["SQL_Eight"]; public static string SQL_Nine = System.Configuration.ConfigurationManager.AppSettings["SQL_Nine"]; //门禁记录SQL语句:微信 public static string MJ_One = System.Configuration.ConfigurationManager.AppSettings["MJ_One"]; public static string MJ_Two = System.Configuration.ConfigurationManager.AppSettings["MJ_Two"]; public static string MJ_Three = System.Configuration.ConfigurationManager.AppSettings["MJ_Three"]; //门禁记录相同方向 public static string MJ_Same_one = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_one"]; public static string MJ_Same_two = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_two"]; public static string MJ_Same_three = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_three"]; public static string MJ_Same_four = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_four"]; public static string MJ_Same_five = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_five"]; public static string MJ_Same_six = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_six"]; public static string MJ_Same_seven = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_seven"]; //门禁记录相同相反方向 public static string MJ_Same_Contrary_one = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_one"]; public static string MJ_Same_Contrary_two = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_two"]; public static string MJ_Same_Contrary_three = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_three"]; public static string MJ_Same_Contrary_four = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_four"]; public static string MJ_Same_Contrary_five = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_five"]; public static string MJ_Same_Contrary_six = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_six"]; public static string MJ_Same_Contrary_seven = System.Configuration.ConfigurationManager.AppSettings["MJ_Same_Contrary_seven"]; //门禁记录:短信 public static string MJ_SMS_one = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_one"]; public static string MJ_SMS_two = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_two"]; //门禁记录相同&&相反方向 public static string MJ_SMS_Same_Contrary_one = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_Same_Contrary_one"]; public static string MJ_SMS_Same_Contrary_two = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_Same_Contrary_two"]; public static string MJ_SMS_Same_Contrary_three = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_Same_Contrary_three"]; public static string MJ_SMS_Same_Contrary_four = System.Configuration.ConfigurationManager.AppSettings["MJ_SMS_Same_Contrary_four"]; public static string DoorSwitchList = System.Configuration.ConfigurationManager.AppSettings["doorSwitchList"]; private static SendMsgByAccessControlRecord _instance; public static SendMsgByAccessControlRecord Instance { get { if (_instance == null) { _instance = new SendMsgByAccessControlRecord(); } return _instance; } } #endregion public static string blackPath = System.Configuration.ConfigurationManager.AppSettings["blackPath"]; public static List blackList = new List(); public SendMsgByAccessControlRecord() { string path = blackPath; Console.WriteLine(path); try { OpenFileWS(path + @"\白名单.txt"); Console.WriteLine($"加载名单列表:{blackList.Count}"); } catch (Exception ex) { Console.WriteLine("加载文本异常:" + ex.Message); } } //open file with SteamReader private void OpenFileWS(string filePath) { FileStream fileStream = new FileStream(filePath, FileMode.Open); StreamReader sr = new StreamReader(fileStream); string line; while ((line = sr.ReadLine()) != null) { //Console.WriteLine(line.ToString()); string str = line.ToString(); try { if (string.IsNullOrEmpty(str)) { continue; } string[] aaa = str.Split('+'); if (aaa.Length > 1) { blackList.Add(new BlackModel() { UserNo = aaa[0], Mobile = aaa[1] }); } else { Console.WriteLine(line.ToString() + " 格式不对。请用XXX+XXX格式"); } } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } } fileStream.Close(); } /** * 调用掌骏后端接口发送家长企业消息和短信 * * */ public ResponseMsgMo sendMsgByAccessControlRecord() { //在门禁记录表中增加字段dataSycFlag数据同步标志:0-未同步;1-同步中;2-已同步 //alter table eastRiver.dbo.PassTime add dataSycFlag int default 0; //update eastRiver.dbo.PassTime set dataSycFlag = 0 where dataSycFlag is null; //获取近2秒的门禁学生进出记录 /** string sql = "select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " //+ ", b.picture " + " from eastRiver.dbo.PassTime a, eastRiver.dbo.PassPicRecords b " + " where a.card_id = b.Card_No and a.passTime = b.PassTime " + " and a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " + " and DATEDIFF(ss, a.passTime, GETDATE() ) <= " + seconds + " "; **/ /** string sql = "select aa.*, b.status_id, b.enrollNumber " + " from (" + " select a.id, a.card_id, a.emp_id, a.door_id, a.temperature, a.passTime, a.inOutFlag, a.evenFlag " + ", b.picture " + " from eastRiver.dbo.PassTime a, eastRiver.dbo.PassPicRecords b " + " where a.card_id = b.Card_No and a.passTime = b.PassTime " + " and a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " + " and DATEDIFF(ss, a.passTime, GETDATE() ) <= " + seconds + " " + " ) aa " + " left join [EastRiver].[dbo].[Employee] b " + " on aa.emp_id=b.emp_id ";**/ //延时timeDelay(10秒)获取记录 int _seconds = (seconds == null || seconds.Length <= 0) ? 0 : int.Parse(seconds); //_seconds += timeDelay; //string sql = "select aa.*, b.status_id " // + " from (" // + " select a.id, a.card_id, a.emp_id, a.door_id, a.temperature, a.passTime, a.inOutFlag, a.evenFlag, a.subdeviceid " // //+ ", b.picture " // + " from eastRiver.dbo.PassTime a " // //+ " where a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " // + " where 1=1 and dataSycFlag = 0 "; // if( _seconds > 0 ) // { // sql += " and DATEDIFF(ss, a.passTime, GETDATE() ) <= " + _seconds + " "; // sql += " and DATEDIFF(ss, a.passTime, GETDATE() ) >= " + timeDelay + " "; // } // sql += " ) aa "; // sql += " left join [EastRiver].[dbo].[Employee] b "; // sql += " on aa.emp_id=b.emp_id "; // sql += " order by aa.passTime "; string sql = SQL_One + SQL_Two + SQL_Three + SQL_Four + SQL_Five; if (_seconds > 0) { sql += SQL_IF_One + timeDelay + SQL_IF_One_a + _seconds + SQL_IF_One_b; } sql += SQL_Six + SQL_Seven + SQL_Eight + SQL_Nine; //log4netService.Debug("_seconds" + _seconds); //log4netService.Debug("sql:" + sql); //log4netService.Debug($"测试SQL={sql}"); DataSet ds = da.ExecuteDataSet(System.Data.CommandType.Text, sql); DataTable dt = ds.Tables[0]; List list = new List(); AccessControlRecord accessControlRecord = new AccessControlRecord(); //log4netService.Debug($"总共获取{dt.Rows.Count},SQL={sql}"); //Console.WriteLine("待处理记录数:" + dt.Rows.Count); //log4netService.Debug("biao" + dt.Rows.Count); if (dt.Rows.Count > 0) { //增加门禁单向门控制开关 Dictionary dicDoorSwitch = new Dictionary(); Console.WriteLine($"屏蔽门号:{DoorSwitchList}"); if (!string.IsNullOrEmpty(DoorSwitchList)) { List doorSwitch = DoorSwitchList.Split(',').ToList(); Console.WriteLine($"总计:{doorSwitch.Count}"); if (doorSwitch.Count > 0) { foreach (string str in doorSwitch) { string[] array = str.Split(':'); dicDoorSwitch.Add(array[0], array[1]); } foreach (KeyValuePair kv in dicDoorSwitch) { Console.WriteLine("输出:"+ kv.Key + kv.Value); } } } for (int i = dt.Rows.Count - 1; i >= 0; i--) { try { if (!shieldDoor.Contains(dt.Rows[i]["door_id"].ToString())) { //============ string doorIdTemp = dt.Rows[i]["door_id"].ToString(); //判断单向门控制 if (dicDoorSwitch.Count > 0 && dicDoorSwitch.Keys.Contains(doorIdTemp)) { string subDeviceId = dt.Rows[i]["subdeviceid"].ToString(); Console.WriteLine("测试:"+subDeviceId); //条件符合,屏蔽 if (subDeviceId == dicDoorSwitch[doorIdTemp]) { //剔除屏蔽的记录 Console.WriteLine($"单向门屏蔽剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); log4netService.Debug($"剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); dt.Rows[i].Delete(); UpdateDataSycFlag(int.Parse(dt.Rows[i]["id"].ToString()), 2); continue; } } //======================== string str1 = dt.Rows[i]["temperature"].ToString(); double db = 0.00; if (str1 != "" && Double.TryParse(str1, out db) != true && db > Convert.ToDouble(_temperature)) { if (dt.Rows[i].RowState == DataRowState.Deleted) { continue; } else { string str = $"因温度或屏蔽门禁过滤数据ID:{dt.Rows[i]["id"]}"; log4netService.Debug(str); Console.WriteLine(str); dt.Rows[i].Delete(); UpdateDataSycFlag(Convert.ToInt32(dt.Rows[i]["id"]), 3); } } } else { //剔除屏蔽的记录 Console.WriteLine($"剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); log4netService.Debug($"剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); dt.Rows[i].Delete(); UpdateDataSycFlag(int.Parse(dt.Rows[i]["id"].ToString()), 2); } } catch (Exception ex) { log4netService.Error($"过滤数据出现错误:{ex.Message},详情:{ex.ToString()}"); } } dt.AcceptChanges(); foreach (DataRow dr in dt.Rows) { if (dr.RowState == DataRowState.Deleted) continue; int id = int.Parse(dr["id"].ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 1); string card_id = dr["card_id"].ToString(); //人事资料卡号 string emp_id = dr["emp_id"].ToString(); string subdeviceid = dr["subdeviceid"].ToString(); int door_id = int.Parse(dr["door_id"].ToString()); double temperature = 0.00; if (dr["temperature"].ToString() != null && dr["temperature"].ToString() != "") { temperature = Convert.ToDouble(dr["temperature"].ToString()); } double temperatureTmp = (_temperature == null || _temperature == "") ? 0.0 : Convert.ToDouble(_temperature); //判断学号是否在黑名单里面 List blacks = blackList.Where(x => x.UserNo == emp_id).ToList(); int isblack = 0; string mobiles = ""; if (blacks.Count > 0) { isblack = 1; foreach (var item in blacks) { mobiles += item.Mobile + ","; } mobiles = mobiles.Trim(','); Console.WriteLine($"{emp_id}在白名单,推送给后台处理.isblack={isblack},mobiles={mobiles}"); //UpdateDataSycFlag(id, 2); //continue; } //双精度误差 var DOUBLE_DELTA = 1E-6; //温度控制不推送消息,由于门禁配置大于等于这个温度不开门。 if (temperature - temperatureTmp > DOUBLE_DELTA || temperature == temperatureTmp) { log4netService.Debug("门禁记录温度[" + temperature + "]大于等于控制温度[" + temperatureTmp + "]"); Console.WriteLine("门禁记录温度[" + temperature + "]大于等于控制温度[" + temperatureTmp + "]"); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 2); continue; } DateTime passTime = Convert.ToDateTime(dr["passTime"].ToString()); int inOutFlag = int.Parse(dr["inOutFlag"].ToString()); int evenFlag = int.Parse(dr["evenFlag"].ToString()); //evenFlag=128是非法卡 if (evenFlag == 128) { Console.WriteLine($"非法卡,不处理"); continue; } log4netService.Debug($"进出方向:{inOutFlag}"); //两次门禁考勤记录间相同方向在60秒(1分钟)内,不推送微信;为0时都推送。 int twoRecordSameTimes = (_twoRecordSameTimes == null || _twoRecordSameTimes == "") ? 0 : int.Parse(_twoRecordSameTimes); //两次门禁考勤记录间相反方向在60秒(1分钟)内,不推送微信;为0时都推送。 int twoRecordContraryTimes = (_twoRecordContraryTimes == null || _twoRecordContraryTimes == "") ? 0 : int.Parse(_twoRecordContraryTimes); //两次门禁考勤记录间在60秒(1分钟)内,不推送短信;为0时都推送。 int twoRecordSMSTimes = (_twoRecordSMSTimes == null || _twoRecordSMSTimes == "") ? 0 : int.Parse(_twoRecordSMSTimes); string status_id = dr["status_id"].ToString(); //学生类型:55 住宿;66 走读;其他(0,77,null) int device_type = 1; //门禁设备类型:1-依时利 int validTimeLeave = (_validTimeLeave == null || _validTimeLeave == "") ? 0 : int.Parse(_validTimeLeave); //请假签到有效时间内1800秒(30分钟) int isAttendanceSend = 1; //是否考勤发送微信消息:0-不推送; 1-推送。 int isAttendanceSMSSend = 1; //是否考勤发送短信消息:0-不推送; 1-推送。 string wxMessageFailReason = ""; //微信消息失败原因:如:黑名单限制、间隔时间限制、学生类型推送时间限制 string smsMessageFailReason = ""; //短信消息失败原因:如:黑名单限制、间隔时间限制、学生类型推送时间限制 int dealFlag = 0; //处理标志:0-未处理; 1-处理中;2-已处理. //string enrollNumber = dr["enrollNumber"] == null ? null : dr["enrollNumber"].ToString(); //人事资料登记号 //byte[] imagePicture = dr["picture"] == null ? null : (byte[])dr["picture"]; //image转换为string //string picture = imagePicture == null ? null : Convert.ToBase64String(imagePicture); //string picture = ""; //byte[]转换为字符串 //picture = System.Text.ASCIIEncoding.Unicode.GetString(pictureTmp); string fileName = ""; //人脸识别照片路径(人事资料登记号+时间命名)D:\Program Files (x86)\EastRiver\Documents\FRPic\[yyyyMMddhhmmss] //D:\Program Files (x86)\EastRiver\通讯前置\Documents\SnapPhoto\180\2022-03-28 //string enrollNumberFileName = frpicPath + "/" + passTime.ToString("yyyy-MM-dd") + "/" + emp_id + "_" + passTime.ToString("yyyyMMddHHmmss") + ".jpg"; string enrollNumberFileName = "";// frpicPath + "/" + passTime.ToString("yyyy-MM-dd") + "/" + subdeviceid + "_" + passTime.ToString("yyyyMMddHHmmss") + ".jpg"; //刷卡抓拍路径 (人事资料卡号+时间命名)D:\Program Files (x86)\EastRiver\Documents\DoorPic\[yyyyMMddhhmmss] string cardIdFileName = doorPicPath + "/" + passTime.ToString("yyyyMMdd") + "/" + card_id + passTime.ToString("yyyyMMddHHmmss") + ".jpg"; //foreach (var item in FacePathDoor) //{ // log4netService.Debug("Door_ID:" + item); //} //log4netService.Debug("Door_id" + dr["door_id"] + "IF:" + ((IList)FacePathDoor).Contains(dr["door_id"])); string str = string.Join("", FacePathDoor); if (str.IndexOf(dr["door_id"].ToString()) > -1) { enrollNumberFileName = FacePath + "/" + dr["door_id"].ToString().Trim() + "/" + passTime.ToString("yyyy-MM-dd") + "/" + emp_id + "_" + passTime.ToString("yyyyMMddHHmmss") + ".jpg"; log4netService.Debug("第二路径:" + enrollNumberFileName); } else { enrollNumberFileName = frpicPath + "/" + passTime.ToString("yyyy-MM-dd") + "/" + emp_id + "_" + passTime.ToString("yyyyMMddHHmmss") + ".jpg"; log4netService.Debug("源路径:" + enrollNumberFileName); } //文件是否存在 if (File.Exists(enrollNumberFileName)) { fileName = enrollNumberFileName; } else { if (File.Exists(cardIdFileName)) { fileName = cardIdFileName; } else { fileName = null; } } //Console.WriteLine("文件名:" + fileName); if (fileName != null && fileName.Length > 0) { //上传图片文件前检查服务端文件是否存在。 Boolean fileCheckFlag = checkDoorImage(passTime.ToString("yyyyMMdd"), Path.GetFileName(fileName)); //检查通过时,上传图片 if (fileCheckFlag) { try { UploadRequest(passTime.ToString("yyyyMMdd"), fileName); } catch (Exception ex) { log4netService.Error("上传图片异常:" + ex.Message); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 0); continue; } log4netService.Info("上传门禁人脸识别图片成功,文件名:" + Path.GetFileName(fileName)); } } Boolean bl = false; //log4netService.Debug("是学生类型:" + status_id + "温度:" + temperature); Console.WriteLine("学生学号:" + emp_id + " 学生类型:" + status_id + " 温度:" + temperature); if (passTime != null && (inOutFlag == 1 || inOutFlag == 2)) { //第一步规则检查, //两次门禁考勤记录间相同方向在60秒(1分钟)内,不推送微信;为0时都推送。 //两次门禁考勤记录间相反方向在60秒(1分钟)内,不推送微信;为0时都推送。 if (twoRecordSameTimes == 0 && twoRecordContraryTimes == 0) { isAttendanceSend = 1; //推送微信(门禁考勤) } else { //检查与本次刷卡的方向 int checkInOutFlag = 0; /** if (inOutFlag == 1) { checkInOutFlag = 2; } else if (inOutFlag == 2) { checkInOutFlag = 1; }**/ checkInOutFlag = inOutFlag; //门禁考勤系统记录检验,检查本次记录与上次记录的时间范围 log4netService.Debug("[检测微信]===="); //Console.WriteLine($"twoRecordSameTimes={twoRecordSameTimes},twoRecordContraryTimes={twoRecordContraryTimes}"); //bl = doTwoRecordTimesCheck(passTime, checkInOutFlag, twoRecordSameTimes, twoRecordContraryTimes, emp_id, id); //进 isAttendanceSend = 1; //推送微信(门禁考勤) if (!CheckPush(emp_id, passTime.ToString())) { isAttendanceSend = 0; //不推送微信(门禁考勤) wxMessageFailReason = "间隔时间限制"; Console.WriteLine("不推送微信"); log4netService.Debug("不推送微信"); } if (inOutFlag == 2 && !CheckPushIn(emp_id, passTime.ToString())) { isAttendanceSend = 0; //不推送微信(门禁考勤) wxMessageFailReason = "间隔时间限制"; Console.WriteLine("不推送微信"); log4netService.Debug("不推送微信"); } if (inOutFlag == 1 && !CheckPushOut(emp_id, passTime.ToString())) { isAttendanceSend = 0; //不推送微信(门禁考勤) wxMessageFailReason = "间隔时间限制"; Console.WriteLine("不推送微信"); log4netService.Debug("不推送微信"); } //Console.WriteLine($"推送微信"); //isAttendanceSend = 1; //推送微信(门禁考勤) //log4netService.Debug("推送微信"); } //第一步规则检查, //两次门禁考勤记录间在60秒(1分钟)内,不推送短信;为0时都推送。 if (twoRecordSMSTimes == 0) { isAttendanceSMSSend = 1; //推送短信(门禁考勤) } else { log4netService.Debug("[短信检测]---检查两次门禁考勤记录=短信"); //门禁考勤系统记录检验,检查本次记录与上次记录的时间范围 //bl = doTwoRecordTimesSMSCheck(passTime, twoRecordSMSTimes, emp_id, id); bool fl = CheckPushSMS(emp_id, passTime.ToString()); //log4netService.Debug(bl + "---" + passTime + "---" + twoRecordSMSTimes + "---" + emp_id + "---" + id); if (!fl) { isAttendanceSMSSend = 0; //不推送短信(门禁考勤) smsMessageFailReason = "间隔时间限制"; } else { isAttendanceSMSSend = 1; //推送短信(门禁考勤) } //log4netService.Debug("isAttendanceSMSSend:" + isAttendanceSMSSend); } } //是学生时,作住宿生、走读生按二次检查(周一到周日开放时间段) //if (status_id == "55" || status_id == "66") if (status_id == boarder_student || status_id == extern_student) { if (isAttendanceSend == 1) { //门禁考勤系统记录检验,根据刷卡或刷脸时间检查是否需要推送消息。 bl = doCheck(passTime, inOutFlag, status_id); if (!bl) { isAttendanceSend = 0; //不推送微信(门禁考勤) wxMessageFailReason = "学生类型推送时间限制"; } else { isAttendanceSend = 1; //推送微信(门禁考勤) } } //第一步规则检查结果为推送消息 if (isAttendanceSMSSend == 1) { //门禁考勤系统记录检验,根据刷卡或刷脸时间检查是否需要推送消息。 bl = doCheck(passTime, inOutFlag, status_id); if (!bl) { isAttendanceSMSSend = 0; //不推短信(门禁考勤) smsMessageFailReason = "学生类型推送时间限制"; } else { isAttendanceSMSSend = 1; //推送短信(门禁考勤) } } } //除了学生类型55-住宿生;66-走读生需要控制;77-全日通行类型等其他类型 else { ; //无需作二次检查(周一到周日开放时间段) } //accessControlRecord = new AccessControlRecord(); //log4netService.Info("门禁记录ID:" + id ); list.Add(new AccessControlRecord() { id = id, card_id = card_id, emp_id = emp_id, door_id = door_id, temperature = temperature, //测温 passTime = passTime, inOutFlag = inOutFlag, //进出门标志:1-出门;2-进门 evenFlag = evenFlag, //picture = picture, //图片抓拍二进制 picture = fileName == null ? null : Path.GetFileName(fileName), //存放文件名 //twoRecordTimes = twoRecordSMSTimes, //两次门禁考勤记录间在60秒(1分钟)内,不推送短信;为0时都推送。 twoRecordSameTimes = twoRecordSameTimes, //两次门禁考勤记录间相同方向在60秒(1分钟)内,不推送微信;为0时都推送。 twoRecordContraryTimes = twoRecordContraryTimes, //两次门禁考勤记录间相反方向在60秒(1分钟)内,不推送微信;为0时都推送。 twoRecordSMSTimes = twoRecordSMSTimes, //两次门禁考勤记录间在60秒(5分钟)内,不推送短信;为0时都推送。 status_id = status_id, //学生类型:55 住宿;66 走读;77-全天通行;其他(0,77,null) device_type = device_type, //门禁设备类型:1-依时利 validTimeLeave = validTimeLeave, //请假签到有效时长(秒) isAttendanceSend = isAttendanceSend, //是否考勤发送微信消息:0-不推送; 1-推送。 isAttendanceSMSSend = isAttendanceSMSSend, //是否考勤发送微信消息:0-不推送; 1-推送。 wxMessageFailReason = wxMessageFailReason, //微信消息失败原因:如:黑名单限制、间隔时间限制、学生类型推送时间限制 smsMessageFailReason = smsMessageFailReason, //短信消息失败原因:如:黑名单限制、间隔时间限制、学生类型推送时间限制 dealFlag = dealFlag, //处理标志:0-未处理; 1-处理中;2-已处理. corpId = corpId, isblack = isblack, mobiles = mobiles }); } } else { //log4netService.Info(DateTime.Now.ToString("u") + "门禁监控中......"); return null; } try { string errmsg = ""; if (string.IsNullOrEmpty(sendMsgByAccessControlRecordUrl)) { if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步;3-屏蔽机号出入 UpdateDataSycFlag(id, 0); } } errmsg = "调用推送学生进出学校消息接口URL为空!"; log4netService.Error(errmsg); return null; } if (string.IsNullOrEmpty(corpId)) { if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 0); } } errmsg = "调用推送学生进出学校消息接口URL为空!"; log4netService.Error(errmsg); return null; } string httpUrl = sendMsgByAccessControlRecordUrl; string requestUrl = string.Format("{0}", httpUrl); //log4netService.Debug("requestUrl:" + requestUrl); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //加上这一句 StreamReader reader; Uri requestUri = new Uri(requestUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.KeepAlive = true; /** * 接口调用的超时时间,默认为3000,单位毫秒 */ request.Timeout = 30000; StringBuilder data = new StringBuilder(); data.Append(string.Format("?t={0}", DateTime.Now.ToString())); if (!string.IsNullOrEmpty(corpId)) { data.Append("&corpId=" + corpId); } if (list != null && list.Count >= 0) { string listStr = Newtonsoft.Json.JsonConvert.SerializeObject(list); data.Append("&data=" + listStr); } //log4netService.Debug("请求data:" + data.ToString() ); byte[] byteData = UTF8Encoding.GetEncoding("utf-8").GetBytes(data.ToString()); request.ContentLength = byteData.Length; // 开始请求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } WebResponse response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); StringBuilder builder = new StringBuilder(); char[] buffer = new char[0x400]; int charCount = 0; while ((charCount = reader.Read(buffer, 0, buffer.Length)) > 0) { builder.Append(buffer, 0, charCount); } reader.Close(); string result = builder.ToString(); if (string.IsNullOrEmpty(result)) { if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 0); } } errmsg = "未知异常"; log4netService.Error(errmsg); return null; } //反序列化Json数据 ResponseMsgMo rpm = JsonConvert.DeserializeObject(result);//result为上面的Json数据 string errCode = rpm.errCode; string leaveInfoStr = rpm.data; //log4netService.Debug("响应errCode:" + errCode + " 上传记录leaveInfoStr:" + leaveInfoStr); if (errCode == "0000") { if (leaveInfoStr == null || leaveInfoStr.Length <= 0) { } else { //errmsg = "调用推送学生进出学校消息接口成功!"; //errmsg = "推送签到消息成功!"; errmsg = "门禁考勤数据上传成功!\r\n"; log4netService.Info(errmsg + leaveInfoStr); Console.WriteLine(errmsg + leaveInfoStr); if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 2); } } } return rpm; } else { if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 2); } } errmsg = rpm.errMsg; log4netService.Error("调用推送学生进出学校消息接口失败,错误码[" + errCode + "]错误信息[" + errmsg + "]"); return rpm; } } catch (Exception ex) { if (list != null && list.Count > 0) { foreach (AccessControlRecord acr in list) { //int id = int.Parse(acr.card_id.ToString()); int id = int.Parse(acr.id.ToString()); //更新门禁记录为数据同步标志DataSycFlag为:0-未同步;1-同步中;2-已同步 UpdateDataSycFlag(id, 0); } } log4netService.Error("调用推送学生进出学校消息接口异常:" + ex.Message + "详情:" + ex.ToString()); } return null; } //根据刷卡或刷脸时间、进出门标志检查是否需要推送消息。 public Boolean doCheck(DateTime passTime, int inOutFlag, string status_id) { try { //需要推送消息的时间段 string times = ""; //根据日期时间获取星期几,0-星期日 int week = CaculateWeekDay(passTime); //log4netService.Debug("刷卡日期:" + passTime + " 是星期:" + week + passTime); //截取时间 string time = passTime.ToLongTimeString().ToString(); //学生类型:55 住宿;66 走读;77-全日能行;其他(0,77,null) //if (status_id == "55") Boolean bl = true; if (int.Parse(swichTime.ToString()) == 1)//时间启用关闭 { if (status_id == boarder_student) { //进出门标志inOutFlag:1-出门;2-进门 if (inOutFlag == 1) { if (week == 1) { times = out_boarder_monday; } else if (week == 2) { times = out_boarder_tuesday; } else if (week == 3) { times = out_boarder_wednesday; } else if (week == 4) { times = out_boarder_thursday; } else if (week == 5) { times = out_boarder_friday; } else if (week == 6) { times = out_boarder_saturday; } else if (week == 0) { times = out_boarder_sunday; } else { return true; } } //进出门标志inOutFlag:1-出门;2-进门 else if (inOutFlag == 2) { if (week == 1) { times = in_boarder_monday; } else if (week == 2) { times = in_boarder_tuesday; } else if (week == 3) { times = in_boarder_wednesday; } else if (week == 4) { times = in_boarder_thursday; } else if (week == 5) { times = in_boarder_friday; } else if (week == 6) { times = in_boarder_saturday; } else if (week == 0) { times = in_boarder_sunday; } else { return true; } } } //走读生 //else if (status_id == "66") else if (status_id == extern_student) { //进出门标志inOutFlag:1-出门;2-进门 if (inOutFlag == 1) { if (week == 1) { times = out_extern_monday; } else if (week == 2) { times = out_extern_tuesday; } else if (week == 3) { times = out_extern_wednesday; } else if (week == 4) { times = out_extern_thursday; } else if (week == 5) { times = out_extern_friday; } else if (week == 6) { times = out_extern_saturday; } else if (week == 0) { times = out_extern_sunday; } else { return true; } } //进出门标志inOutFlag:1-出门;2-进门 else if (inOutFlag == 2) { if (week == 1) { times = in_extern_monday; } else if (week == 2) { times = in_extern_tuesday; } else if (week == 3) { times = in_extern_wednesday; } else if (week == 4) { times = in_extern_thursday; } else if (week == 5) { times = in_extern_friday; } else if (week == 6) { times = in_extern_saturday; } else if (week == 0) { times = in_extern_sunday; } else { return true; } } } else { return true; } //可推送时间段为空时 if (times == null || times == "") { return true; } //判断门禁时间是否在可推送消息的时间段内 bl = doTimeCheck(time, times); } else { bl = true; } //log4netService.Debug("判断门禁时间是否在可推送消息的时间段内:检验结果[" + bl + "]、times[" + times + "]、time[" + time + "]"); return bl; } catch (Exception e) { log4netService.Error("根据刷卡或刷脸时间、进出门标志检查处理异常:" + e.Message); return false; } } /// /// 计算指定日期的星期值。星期日为0,其他为对应的星期值 /// 默认返回:int类型的星期值 /// /// A System.DateTime public int CaculateWeekDay(DateTime rq) { int y = rq.Year; int m = rq.Month; int d = rq.Day; if (m == 1 || m == 2) { m += 12; y--; } int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400 + 1) % 7; return week; } /// /// 检查刷卡时间是否在设置的时间段内(多个)时 /// 默认返回:int类型的星期值 /// /// A System.DateTime public Boolean doTimeCheck(string time, string times) { try { Boolean bl = false; string[] timesArray = times.Split(';'); //时间段为空或不存在时,默认要推送。 if (timesArray == null || timesArray.Length <= 0) { return true; } string startTime = ""; string endTime = ""; string newTime = ""; for (int i = 0; i < timesArray.Length; i++) { newTime = timesArray[i]; //log4netService.Debug("时间段:" + newTime); //Console.WriteLine("时间段:", newTime); string[] newTimeArray = newTime.Split('~'); if (newTimeArray.Length != 2) { log4netService.Error("时间格式错误:" + newTime); return false; } startTime = newTimeArray[0].Trim(); if (startTime.Length == 5) { startTime += ":00"; } //时间格式检验 bl = IsTime(startTime); if (!bl) { log4netService.Error("开始时间格式错误:" + newTimeArray[0].Trim()); return false; } endTime = newTimeArray[1].Trim(); if (endTime.Length == 5) { endTime += ":59"; } //时间格式检验 bl = IsTime(endTime); if (!bl) { log4netService.Error("截止时间格式错误:" + newTimeArray[1].Trim()); return false; } DateTime dateTime = Convert.ToDateTime(time); DateTime dateStartTime = Convert.ToDateTime(startTime); DateTime dateEndTime = Convert.ToDateTime(endTime); //log4netService.Debug("dateTime:" + dateTime); //log4netService.Debug("dateStartTime:" + dateStartTime); //log4netService.Debug("dateEndTime:" + dateEndTime); //时间比较,参数1>参数2=1;参数1<参数2=-1;参数1=参数2=0; if (DateTime.Compare(dateStartTime, dateEndTime) >= 0) { continue; } //刷卡时间在时间段之外 if (DateTime.Compare(dateTime, dateStartTime) < 0 || DateTime.Compare(dateTime, dateEndTime) > 0) { Console.WriteLine($"刷卡时间在时间段之外"); continue; } //在时间段内时,要推送。 else { return true; } } return false; } catch (Exception e) { log4netService.Error("检查刷卡时间是否在设置的时间段内处理异常:" + e.Message); return false; } } //检查两次门禁考勤记录间同方向在60秒(1分钟)内,不推送微信;为0时都推送。 //检查两次门禁考勤记录间反方向在60秒(1分钟)内,不推送微信;为0时都推送。 public Boolean doTwoRecordTimesCheck(DateTime passTime, int checkInOutFlag, int twoRecordSameTimes, int twoRecordContraryTimes, string emp_id, int id) { try { /** string sql = "select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " + " from eastRiver.dbo.PassTime a, eastRiver.dbo.PassPicRecords b " + " where a.card_id = b.Card_No and a.passTime = b.PassTime " + " and a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " + " and a.inOutFlag = " + checkInOutFlag + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) > 0 " + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) <= " + twoRecordTimes + " and a.emp_id = '" + emp_id + "'"; **/ //string sql = "select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " // + " from eastRiver.dbo.PassTime a " // + " where 1!=1 " // //+ " where a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " // + " and a.emp_id = '" + emp_id + "'"; string sql = MJ_One + MJ_Two + emp_id + MJ_Three; string sql1 = ""; //只检查相同方向 if (twoRecordSameTimes > 0) { //sql1 = " union all select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " // + " from eastRiver.dbo.PassTime a " // + " where 1=1 " // + " and a.emp_id = '" + emp_id + "'" // + " and a.inOutFlag = " + checkInOutFlag // + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) > 0 " // + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) <= " + twoRecordSameTimes; sql1 = MJ_Same_one + MJ_Same_two + emp_id + MJ_Same_three + checkInOutFlag + MJ_Same_four + id + MJ_Same_five + MJ_Same_six + id + MJ_Same_seven + twoRecordSameTimes; } string sql2 = ""; //相同方向和相反方向 if (twoRecordContraryTimes > 0) { //sql2 = " union all select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " // + " from eastRiver.dbo.PassTime a " // + " where 1=1 " // + " and a.emp_id = '" + emp_id + "'" // + " and a.inOutFlag != " + checkInOutFlag // + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) > 0 " // + " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) <= " + twoRecordContraryTimes; sql2 = MJ_Same_Contrary_one + MJ_Same_Contrary_two + emp_id + MJ_Same_Contrary_three + checkInOutFlag + MJ_Same_Contrary_four + id + MJ_Same_Contrary_five + MJ_Same_Contrary_six + id + MJ_Same_Contrary_seven + twoRecordContraryTimes; } sql += sql1 + sql2; log4netService.Debug("sql:" + sql); DataSet ds = da.ExecuteDataSet(System.Data.CommandType.Text, sql); DataTable dt = ds.Tables[0]; //log4netService.Debug("biaobiao" + dt.Rows.Count.ToString()); //剔除微信异常数据 for (int i = dt.Rows.Count - 1; i >= 0; i--) { try { if (!shieldDoor.Contains(dt.Rows[i]["door_id"].ToString())) { string str1 = dt.Rows[i]["temperature"].ToString(); double db = 0.00; if (str1 != "" && Double.TryParse(str1, out db) != true && db > Convert.ToDouble(_temperature)) { if (dt.Rows[i].RowState == DataRowState.Deleted) { continue; } else { string str = $"因温度或屏蔽门禁过滤数据ID:{dt.Rows[i]["id"]}"; UpdateDataSycFlag(Convert.ToInt32(dt.Rows[i]["id"]), 3); log4netService.Debug(str); Console.WriteLine(str); dt.Rows[i].Delete(); } } } else { //剔除屏蔽的记录 Console.WriteLine($"剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); UpdateDataSycFlag(int.Parse(dt.Rows[i]["id"].ToString()), 2); dt.Rows[i].Delete(); } } catch (Exception ex) { log4netService.Error($"过滤上一次数据出现错误:{ex.Message},详情:{ex.ToString()}"); } } dt.AcceptChanges(); //log4netService.Debug("biaobiao" + dt.Rows.Count.ToString()); List list = new List(); AccessControlRecord accessControlRecord = new AccessControlRecord(); if (dt.Rows.Count > 0) { //在twoRecordTimes时间内有记录时,本次第一步检验需不推送 return false; } else { //在twoRecordTimes时间内无记录时,本次第一步检验需推送 return true; } } catch (Exception e) { log4netService.Error("检查在这twoRecordTimes时间之内是否有门禁考勤记录异常:" + e.Message); return false; } } //检查两次门禁考勤记录间在60秒(1分钟)内,不推送短信;为0时都推送。 public Boolean doTwoRecordTimesSMSCheck(DateTime passTime, int twoRecordSMSTimes, string emp_id, int id) { try { //string sql = "select DISTINCT a.id, a.card_id, a.emp_id, a.door_id, a.passTime, a.inOutFlag, a.evenFlag " // + " from eastRiver.dbo.PassTime a " // + " where 1=1 " // //+ " where a.EvenFlag in (0, 1, 2, 3, 4, 5, 6, 7, 211) " // + " and a.emp_id = '" + emp_id + "'"; string sql = MJ_SMS_one + emp_id + MJ_SMS_two; //相同方向和相反方向 if (twoRecordSMSTimes > 0) { //sql += " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) > 0 "; //sql += " and DATEDIFF(ss, a.passTime, (select passTime from eastRiver.dbo.PassTime where id = " + id + " ) ) <= " + twoRecordSMSTimes; sql += MJ_SMS_Same_Contrary_one + id + MJ_SMS_Same_Contrary_two; sql += MJ_SMS_Same_Contrary_three + id + MJ_SMS_Same_Contrary_four + twoRecordSMSTimes; } log4netService.Debug("sql:" + sql); DataSet ds = da.ExecuteDataSet(System.Data.CommandType.Text, sql); DataTable dt = ds.Tables[0]; //剔除推送短信异常 for (int i = dt.Rows.Count - 1; i >= 0; i--) { try { // if ((Convert.ToDecimal(dt.Rows[i]["temperature"]) > Convert.ToDecimal(_temperature) && dt.Rows[i]["temperature"] != null && dt.Rows[i]["temperature"].ToString() != "") || shieldDoor.Contains(dt.Rows[i]["door_id"].ToString())) // { // if (dt.Rows[i].RowState == DataRowState.Deleted) // { // continue; // } // else // { // string str = $"因上一次温度或屏蔽门禁过滤短信推送数据ID:{dt.Rows[i]["id"]}"; // UpdateDataSycFlag(Convert.ToInt32(dt.Rows[i]["id"]), 3); // log4netService.Debug(str); // Console.WriteLine(str); // dt.Rows[i].Delete(); // } // } if (!shieldDoor.Contains(dt.Rows[i]["door_id"].ToString())) { string str1 = dt.Rows[i]["temperature"].ToString(); double db = 0.00; if (str1 != "" && Double.TryParse(str1, out db) != true && db > Convert.ToDouble(_temperature)) { if (dt.Rows[i].RowState == DataRowState.Deleted) { continue; } else { string str = $"因温度或屏蔽门禁过滤数据ID:{dt.Rows[i]["id"]}"; UpdateDataSycFlag(Convert.ToInt32(dt.Rows[i]["id"]), 3); log4netService.Debug(str); Console.WriteLine(str); dt.Rows[i].Delete(); } } } else { //剔除屏蔽的记录 Console.WriteLine($"剔除屏蔽门禁{dt.Rows[i]["door_id"]}"); UpdateDataSycFlag(int.Parse(dt.Rows[i]["id"].ToString()), 2); dt.Rows[i].Delete(); } } catch (Exception ex) { log4netService.Error($"过滤上一次数据出现错误:{ex.Message},详情:{ex.ToString()}"); } } dt.AcceptChanges(); List list = new List(); AccessControlRecord accessControlRecord = new AccessControlRecord(); if (dt.Rows.Count > 0) { /** foreach (DataRow dr in dt.Rows) { int new_id = int.Parse(dr["id"].ToString()); string new_card_id = dr["card_id"].ToString(); //人事资料卡号 string new_emp_id = dr["emp_id"].ToString(); int door_id = int.Parse(dr["door_id"].ToString()); DateTime new_passTime = Convert.ToDateTime(dr["passTime"].ToString()); int new_inOutFlag = int.Parse(dr["inOutFlag"].ToString()); log4netService.Debug("new_id..." + new_id); log4netService.Debug("new_emp_id..." + new_emp_id); log4netService.Debug("new_passTime..." + new_passTime); log4netService.Debug("new_inOutFlag..." + new_inOutFlag); }**/ //在twoRecordTimes时间内有记录时,本次第一步检验需不推送 return false; } else { //在twoRecordTimes时间内无记录时,本次第一步检验需推送 return true; } } catch (Exception e) { log4netService.Error("检查在这twoRecordTimes时间之内是否有门禁考勤记录异常:" + e.Message); return false; } } /// /// 是否为时间型字符串 /// /// 时间字符串(15:00:00) /// public Boolean IsTime(string StrSource) { return Regex.IsMatch(StrSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$"); } /// /// 上传图片文件前检查服务端文件是否存在 /// /// public Boolean checkDoorImage(string dateFolder, string fileName) { //log4netService.Debug("checkDoorImage...记录日期:" + dateFolder + " 文件名:" + fileName); try { string errmsg = ""; string httpUrl = checkDoorImageUrl; string requestUrl = string.Format("{0}", httpUrl); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //加上这一句 StreamReader reader; Uri requestUri = new Uri(requestUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.KeepAlive = true; /** * 接口调用的超时时间,默认为3000,单位毫秒 */ request.Timeout = 30000; StringBuilder data = new StringBuilder(); data.Append(string.Format("?t={0}", DateTime.Now.ToString())); if (!string.IsNullOrEmpty(dateFolder)) { data.Append("&dateFolder=" + dateFolder); } if (!string.IsNullOrEmpty(fileName)) { data.Append("&fileName=" + fileName); } if (!string.IsNullOrEmpty(corpId)) { data.Append("&corpId=" + corpId); } //log4netService.Debug("请求data:" + data.ToString() ); byte[] byteData = UTF8Encoding.GetEncoding("utf-8").GetBytes(data.ToString()); request.ContentLength = byteData.Length; // 开始请求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } WebResponse response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); StringBuilder builder = new StringBuilder(); char[] buffer = new char[0x400]; int charCount = 0; while ((charCount = reader.Read(buffer, 0, buffer.Length)) > 0) { builder.Append(buffer, 0, charCount); } reader.Close(); string result = builder.ToString(); if (string.IsNullOrEmpty(result)) { errmsg = "未知异常"; log4netService.Error(errmsg); return true; //异常时,跳过上传图片 } //反序列化Json数据 ResponseMsgMo rpm = JsonConvert.DeserializeObject(result);//result为上面的Json数据 string errCode = rpm.errCode; string errMsg = rpm.errMsg; //log4netService.Debug("服务端门禁人脸识别图片检查:响应码:" + errCode + " 响应信息:" + errMsg); if (errCode == "0000") { return true; } else { if (errmsg != "" && errmsg != "File already exists") { log4netService.Error("错误码[" + errCode + "]错误信息[" + errmsg + "]"); } return false; } } catch (Exception ex) { log4netService.Error("服务端门禁人脸识别图片检查异常:" + ex.Message); return false; } } /// /// C# 中发送POST请求 /// filePath:文件全路径名称 /// /// /// private void UploadRequest(string dateFolder, string filePath) { //Console.WriteLine("UploadRequest..."); //byte[] bytes = image;//Encoding.UTF8.GetBytes(image);//这里需要指定提交的编码 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] bytes = new byte[fs.Length]; try { fs.Read(bytes, 0, (int)fs.Length); } catch (Exception ex) { log4netService.Error("文件处理异常:" + ex.Message); return; } finally { if (fs != null) { //关闭资源 fs.Close(); } } HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadDoorImageUrl); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Accept = "application/x-www-form-urlencoded"; string dataFormat = "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"; dateFolder=\"{2}\"; corpId=\"{3}\"\r\nContent-Type:application/x-www-form-urlencoded\r\n\r\n"; string header = string.Format(dataFormat, "file", Path.GetFileName(filePath), dateFolder, corpId); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header); long length = bytes.Length + postHeaderBytes.Length; //webRequest.ContentLength = bytes.Length; webRequest.ContentLength = length;//请求内容长度 Stream dataStream = webRequest.GetRequestStream(); //头信息 dataStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); //图片信息 dataStream.Write(bytes, 0, bytes.Length); dataStream.Close(); //接收响应 HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); MemoryStream ms = null; using (var stream = webResponse.GetResponseStream()) { Byte[] buffer = new Byte[webResponse.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); ms = new MemoryStream(buffer); } webResponse.Close(); } /// /// double比较大小 /// /// /// /// public static bool DoubleEquals(double value1, double value2) { //双精度误差 var DOUBLE_DELTA = 1E-6; return value1 == value2 || Math.Abs(value1 - value2) < DOUBLE_DELTA; } /// /// 更新数据同步标志 /// /// /// public void UpdateDataSycFlag(int Id, int dataSycFlag) { string sql = "update eastRiver.dbo.PassTime set dataSycFlag=@dataSycFlag where id=@id"; System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = "@id", Value = Id }); cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = "@dataSycFlag", Value = dataSycFlag }); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 10000000; da.ExecuteNonQuery(cmd); } //检测时间间隔,两次不同方向 private Dictionary _hasPush = new Dictionary(); public bool CheckPush(string card, string newTime) { if (this._hasPush.ContainsKey(card)) { string str = this._hasPush[card]; DateTime dateTime1 = Convert.ToDateTime(newTime); DateTime dateTime2 = Convert.ToDateTime(str); int totalSeconds = (int)dateTime1.Subtract(dateTime2).TotalSeconds; if (dateTime1 == dateTime2) return true; log4netService.Debug(string.Format("微信-【进出】卡号:{0},oldTime:{1},newTime{2},间隔总秒数:{3}", (object)card, (object)str, (object)newTime, (object)totalSeconds)); if (totalSeconds < int.Parse(_twoRecordContraryTimes)) return false; this._hasPush.Remove(card); this._hasPush.Add(card, newTime); ; return true; } this._hasPush.Add(card, newTime); return true; } //进来 private Dictionary _hasPushIn = new Dictionary(); public bool CheckPushIn(string card, string newTime) { if (this._hasPushIn.ContainsKey(card)) { string str = this._hasPushIn[card]; DateTime dateTime1 = Convert.ToDateTime(newTime); DateTime dateTime2 = Convert.ToDateTime(str); int totalSeconds = (int)dateTime1.Subtract(dateTime2).TotalSeconds; if (dateTime1 == dateTime2) return true; log4netService.Debug(string.Format("微信-[进]卡号:{0},oldTime:{1},newTime{2},间隔总秒数:{3}", (object)card, (object)str, (object)newTime, (object)totalSeconds)); if (totalSeconds < int.Parse(_twoRecordSameTimes)) return false; this._hasPushIn.Remove(card); _hasPushIn.Add(card, newTime); return true; } _hasPushIn.Add(card, newTime); return true; } private Dictionary _hasPushOut = new Dictionary(); public bool CheckPushOut(string card, string newTime) { if (this._hasPushOut.ContainsKey(card)) { string str = this._hasPushOut[card]; DateTime dateTime1 = Convert.ToDateTime(newTime); DateTime dateTime2 = Convert.ToDateTime(str); int totalSeconds = (int)dateTime1.Subtract(dateTime2).TotalSeconds; if (dateTime1 == dateTime2) return true; log4netService.Debug(string.Format("微信-[出]卡号:{0},oldTime:{1},newTime{2},间隔总秒数:{3}", (object)card, (object)str, (object)newTime, (object)totalSeconds)); if (totalSeconds < int.Parse(_twoRecordSameTimes)) return false; this._hasPushOut.Remove(card); this._hasPushOut.Add(card, newTime); return true; } this._hasPushOut.Add(card, newTime); return true; } //短信 private Dictionary _hasPushSMS = new Dictionary(); public bool CheckPushSMS(string card, string newTime) { if (this._hasPushSMS.ContainsKey(card)) { string str = this._hasPushSMS[card]; DateTime dateTime1 = Convert.ToDateTime(newTime); DateTime dateTime2 = Convert.ToDateTime(str); int totalSeconds = (int)dateTime1.Subtract(dateTime2).TotalSeconds; if (dateTime1 == dateTime2) return true; log4netService.Debug(string.Format("[短信]卡号:{0},oldTime:{1},newTime{2},间隔总秒数:{3}", (object)card, (object)str, (object)newTime, (object)totalSeconds)); if (totalSeconds < int.Parse(_twoRecordSameTimes)) return false; this._hasPushSMS.Remove(card); this._hasPushSMS.Add(card, newTime); return true; } this._hasPushSMS.Add(card, newTime); return true; } } public class BlackModel { public string UserNo { get; set; } public string Mobile { get; set; } } }