From 9a63db00615c07f61292d6a10ca1ad6bfba7f463 Mon Sep 17 00:00:00 2001 From: 1790429840 <1790429840@qq.com> Date: Tue, 30 May 2023 09:53:55 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.vs/WinFormsAppVisitorDeploy/v16/.suo | Bin 65536 -> 92672 bytes WinFormsAppVisitorDeploy/App.config | 4 +- WinFormsAppVisitorDeploy/Form1.Designer.cs | 26 +- WinFormsAppVisitorDeploy/Form1.cs | 600 ++++++++++-------- WinFormsAppVisitorDeploy/MyLogHelper.cs | 262 ++++++++ .../MyTaskControlHelper.cs | 45 ++ .../WinFormsAppVisitorDeploy.csproj | 2 + 7 files changed, 669 insertions(+), 270 deletions(-) create mode 100644 WinFormsAppVisitorDeploy/MyLogHelper.cs create mode 100644 WinFormsAppVisitorDeploy/MyTaskControlHelper.cs diff --git a/WinFormsAppVisitorDeploy/.vs/WinFormsAppVisitorDeploy/v16/.suo b/WinFormsAppVisitorDeploy/.vs/WinFormsAppVisitorDeploy/v16/.suo index 43f7c974d3909b22909c516fcef5d2917cde1e28..d6a0d7d348589c87787132a2b39ef2489e1fa64f 100644 GIT binary patch delta 12935 zcmeHN30&0G_P_VXusR|t0s$f*7#hg137Epjq6jHcE{G^11BxObi!3TLsF_;`b8@W| z5VulG#xk`Gvsb=exz%g2SNbZKr#(|kdz#7rdw(;e{ZoXt*ZX|>@i~0&J@?*o*K^KY zMyFHg-ZQTr(5*jXOaZ#t+}sRc9MoY)(s!II$V2L3`}|{m#jEun@qr?729- zY0cLoeuK))W@-DOOy3S7oiS_B_Yl?c39(k-wZxqfz8}>6wtRL7KL8SWM1JuZOmSnZ zxw#|ay-YkuUJDHr64>GG_fYBt9d#C zQ)`lXhD}2t2b2pEmE-~QK{G(bCSJJ-OH5b+q?6|MRuKqPipUK<0yB10a_^YiRMd_M z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G%Ni4?3UjQ>_5K#m1WKEjK6iO6}v-o{Dl*Q!>JIZjEC7mFy8)nLBBZ_%pjRl zU<*cVhty_G>j&`sRMs5) zHf%fEwHrL6KdK4>yX38={D#$9nL!H+7yayCQsA(SA%-T#J)kQ zx}TIqfV}bPrkQ8RHx(3`IuJ*%X3G}?nWG035Qp_2B`Uc-G))GMHCI)5_-YtdHpR%5 zWETykR_k`ju7(W0_X7vQZL^tQS15!^ z`CZX!pFY=8xds-Y{(7_a8G4f|)Wl1Vcu&;UOw5&S+X;bWX+{WSC=7*pMN(oE#G>=M zPRY0Vnb>uGESk@+iI(Mck-&G4N)8dTZ#pDn2} z9~tnqAsw1WqEsFGs#;pN1QwqFg22QbURqSq|~iRy7!K^(RXBLx2JJ(__X`4dgy<0qxfek|7vYKg|APP9BLxHzoH|{DwSa#}upDXAQs&t;`Kty~;pqq}6bK zjl{L8$=D-Kx{?9H8yfA~TK3d^eLP7D(L*WjzoCi=$hPU0jTjgKt0$*P(k6aq_|&=K zQ%7ESIJfM3IfjoUOgYcrAd>QKQ3%R@I?sb)+S6mYiijnhgHo>^%J>XC*zZlJBgYf< zlM(TMQzd)CgZ@9~?}=BUh%1_+bTPC`l6l`!`wuN;i#q@S diff --git a/WinFormsAppVisitorDeploy/App.config b/WinFormsAppVisitorDeploy/App.config index 8e8dee7..cf960fa 100644 --- a/WinFormsAppVisitorDeploy/App.config +++ b/WinFormsAppVisitorDeploy/App.config @@ -3,7 +3,9 @@ - + + + diff --git a/WinFormsAppVisitorDeploy/Form1.Designer.cs b/WinFormsAppVisitorDeploy/Form1.Designer.cs index 09ab828..1fa6132 100644 --- a/WinFormsAppVisitorDeploy/Form1.Designer.cs +++ b/WinFormsAppVisitorDeploy/Form1.Designer.cs @@ -30,7 +30,7 @@ namespace WinFormsAppVisitorDeploy private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); + this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.SuspendLayout(); // // button1 @@ -44,37 +44,37 @@ namespace WinFormsAppVisitorDeploy this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // - // textBox1 + // richTextBox1 // - this.textBox1.Location = new System.Drawing.Point(10, 37); - this.textBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); - this.textBox1.MaxLength = 327670; - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.textBox1.Size = new System.Drawing.Size(666, 392); - this.textBox1.TabIndex = 1; + this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.richTextBox1.Location = new System.Drawing.Point(10, 38); + this.richTextBox1.Name = "richTextBox1"; + this.richTextBox1.Size = new System.Drawing.Size(664, 403); + this.richTextBox1.TabIndex = 1; + this.richTextBox1.Text = ""; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(686, 453); - this.Controls.Add(this.textBox1); + this.Controls.Add(this.richTextBox1); this.Controls.Add(this.button1); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Name = "Form1"; this.Text = "Form1"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); - this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; - private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.RichTextBox richTextBox1; } } diff --git a/WinFormsAppVisitorDeploy/Form1.cs b/WinFormsAppVisitorDeploy/Form1.cs index b06a590..3ac945e 100644 --- a/WinFormsAppVisitorDeploy/Form1.cs +++ b/WinFormsAppVisitorDeploy/Form1.cs @@ -19,38 +19,69 @@ namespace WinFormsAppVisitorDeploy InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } - - public void Form1_Load(object sender,EventArgs e) + /// + /// 窗口初始化 + /// + /// + /// + public void Form1_Load(object sender, EventArgs e) { StartEventLongHttp(); //开个线程 { - Thread T = new Thread(Test); + Thread T = new Thread(ThreadFunction); //启动新的线程 T.Start(); } } - public void Test() + /// + /// 定时验证是否收到心跳信息 + /// + public void ThreadFunction() { - while(true) - { - Thread.Sleep(20000); - - TimeSpan ts = DateTime.Now - a; //计算时间差 + while (true) + { + Thread.Sleep(10000); + + TimeSpan ts = DateTime.Now - newDataTime; //计算时间差 string time = ts.TotalSeconds.ToString(); //将时间差转换为秒 - if (decimal.Parse(time)>20) + var timLen = decimal.Parse(time); + if (timLen > 30) { + + AppendShowMsg("心跳超时,重新连接," + timLen + "秒"); + LogError("心跳超时,重新连接," + timLen + "秒"); + + //心跳超时,重新连接 + isOne = true; StartEventLongHttp(); + + AppendShowMsg("心跳超时,重新连接执行结束"); + LogError("心跳超时,重新连接执行结束"); + + } + else + { + //心跳未超时 + AppendShowMsg("心跳正常收到数据," + timLen + "秒"); + LogDebug("心跳正常收到数据," + timLen + "秒"); } } } + /// + /// 最新收到信息时间 + /// + DateTime newDataTime = DateTime.Now; - DateTime a = DateTime.Now; - - + /// + /// 访客机服务器IP地址 + /// string strDeviceIp = ConfigurationManager.AppSettings["strDeviceIp"].ToString(); + /// + /// 访客机服务对接接口 + /// string sPort = ConfigurationManager.AppSettings["sPort"].ToString(); string strUserName = ConfigurationManager.AppSettings["strUserName"].ToString(); string strPassword = ConfigurationManager.AppSettings["strPassword"].ToString(); @@ -58,7 +89,6 @@ namespace WinFormsAppVisitorDeploy string DistributeUserUrl = ConfigurationManager.AppSettings["DistributeUserUrl"].ToString(); string strUrl = ConfigurationManager.AppSettings["strUrl"].ToString(); - IAsyncResult ret; public class visitorModel { public string deviceSericeNo { get; set; } @@ -162,10 +192,15 @@ namespace WinFormsAppVisitorDeploy public int totalMatches { get; set; } } + /// + /// 手动初始化操作 + /// + /// + /// - private void button1_Click(object sender, EventArgs e) { + isOne = true; StartEventLongHttp(); } @@ -186,14 +221,33 @@ namespace WinFormsAppVisitorDeploy HttpOther, HttpTimeOut } - - public void text(string info) + /// + /// 添加显示信息 + /// + /// + public void AppendShowMsg(string info) { - if (textBox1.Text.Length > 20000) + try { - textBox1.Text = textBox1.Text.Remove(0, textBox1.Text.Length - 10000); + richTextBox1.BeginInvoke(new Action(() => + { + if (richTextBox1.Text.Length > 50000) + { + richTextBox1.Text = richTextBox1.Text.Substring(richTextBox1.Text.Length - 10000, 10000); + } + + richTextBox1.AppendText(DateTime.Now.ToString() + "\t" + info); + richTextBox1.AppendText(Environment.NewLine); + + richTextBox1.SelectionStart = richTextBox1.TextLength; + richTextBox1.ScrollToCaret(); + + })); + } + catch (Exception ex) + { + LogError("添加显示信息异常:" + ex); } - textBox1.AppendText(info + "\r\n" + textBox1.Text.Length + "\r\n"); } public class RequestState { @@ -241,45 +295,49 @@ namespace WinFormsAppVisitorDeploy //private IDeviceTree m_deviceTree = null; - public class CSubscribeDeviceMgmt - { - public CSubscribeDeviceMgmt() - { - SubscribeDeviceMgmt = new CSubscribeDeviceMgmtInter(); - } - public class CSubscribeDeviceMgmtInter - { - public CSubscribeDeviceMgmtInter() - { - DevEventList = new List(); - } - public string eventMode { get; set; }/*必填,字符型,网关布防事件模式:"device"-布防指定设备*/ - /*"DevEventList"依赖于"eventMode"为"device"*/ - - public class CDevEventListItem - { - public CDevEventListItem() - { - Dev = new CDev(); - } - public class CDev - { - public string devIndex { get; set; } /*必填,字符型,设备唯一标识*/ - public string uploadMode { get; set; }/*必填,字符型,指定设备的事件布防模式:"all"-订阅设备的全部事件*/ - } - public CDev Dev { get; set; } - } - public List DevEventList { get; set; } - } - public CSubscribeDeviceMgmtInter SubscribeDeviceMgmt { get; set; } - } + ////不知道干嘛用的一段 + //public class CSubscribeDeviceMgmt + //{ + // public CSubscribeDeviceMgmt() + // { + // SubscribeDeviceMgmt = new CSubscribeDeviceMgmtInter(); + // } + // public class CSubscribeDeviceMgmtInter + // { + // public CSubscribeDeviceMgmtInter() + // { + // DevEventList = new List(); + // } + // public string eventMode { get; set; }/*必填,字符型,网关布防事件模式:"device"-布防指定设备*/ + // /*"DevEventList"依赖于"eventMode"为"device"*/ + + // public class CDevEventListItem + // { + // public CDevEventListItem() + // { + // Dev = new CDev(); + // } + // public class CDev + // { + // public string devIndex { get; set; } /*必填,字符型,设备唯一标识*/ + // public string uploadMode { get; set; }/*必填,字符型,指定设备的事件布防模式:"all"-订阅设备的全部事件*/ + // } + // public CDev Dev { get; set; } + // } + // public List DevEventList { get; set; } + // } + // public CSubscribeDeviceMgmtInter SubscribeDeviceMgmt { get; set; } + //} + /// + /// 开始执行接收访客机登记信息 + /// + /// public int StartEventLongHttp() { - a = DateTime.Now; string strparam = ""; string strHttpMethod = "GET"; @@ -302,6 +360,7 @@ namespace WinFormsAppVisitorDeploy return iRet; } + /// /// 匹配相同的子byte数组 /// /// 目标byte序列 @@ -310,39 +369,46 @@ namespace WinFormsAppVisitorDeploy /// 参数错误或未匹配到返回-1,否则返回value在src上出现的位置 internal int IndexOf(byte[] src, int index, byte[] value) { - if (src == null || value == null) + try { - return -1; - } + if (src == null || value == null) + { + return -1; + } - if (src.Length == 0 || src.Length < index - || value.Length == 0 || src.Length < value.Length) - { - return -1; - } - for (int i = index; i < src.Length - value.Length; i++) - { - if (src[i] == value[0]) + if (src.Length == 0 || src.Length < index + || value.Length == 0 || src.Length < value.Length) { - if (value.Length == 1) - { - return i; - } - bool flag = true; - for (int j = 1; j < value.Length; j++) + return -1; + } + for (int i = index; i < src.Length - value.Length; i++) + { + if (src[i] == value[0]) { - if (src[i + j] != value[j]) + if (value.Length == 1) { - flag = false; - break; + return i; + } + bool flag = true; + for (int j = 1; j < value.Length; j++) + { + if (src[i + j] != value[j]) + { + flag = false; + break; + } + } + if (flag) + { + return i; } - } - if (flag) - { - return i; } } } + catch (Exception ex) + { + LogError("数组匹配异常:" + ex); + } return -1; } @@ -350,7 +416,6 @@ namespace WinFormsAppVisitorDeploy string strdatatime = ""; int piccount = 0; - HttpWebRequest request; public class CHeartBeat { @@ -591,9 +656,10 @@ namespace WinFormsAppVisitorDeploy } catch (Exception e) { - Console.WriteLine("ParseAlarmData Exception raised!"); - Console.WriteLine("\nMessage:{0}", e.Message); - text("ParseAlarmData:" + e.Message); + AppendShowMsg("ParseAlarmData方法执行异常:" + e.Message); + + LogError("ParseAlarmData方法执行异常" + e); + return false; } @@ -611,11 +677,12 @@ namespace WinFormsAppVisitorDeploy //} - public class ContantData - { - public string ContentType { get; set; } - public byte[] Content { get; set; } - } + ////不知道干嘛用的一段 + //public class ContantData + //{ + // public string ContentType { get; set; } + // public byte[] Content { get; set; } + //} public class PackageData { @@ -672,9 +739,9 @@ namespace WinFormsAppVisitorDeploy { } } - catch(Exception e) + catch (Exception e) { - text("SplitPackage:" + e.Message); + AppendShowMsg("SplitPackage:" + e.Message); } } int endLength = pBuf.Length - endindex; @@ -720,7 +787,8 @@ namespace WinFormsAppVisitorDeploy catch (Exception e) { statusString = httpBody; - text("ParserResponseStatus:" + e.Message); + AppendShowMsg("ParserResponseStatus方法执行异常:" + e.Message); + LogDebug("ParserResponseStatus方法执行异常:" + e); } return 0; } @@ -735,17 +803,30 @@ namespace WinFormsAppVisitorDeploy } if (strURL != sUrl) { - _credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword)); - strURL = sUrl; + try + { + _credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword)); + strURL = sUrl; + } + catch (Exception ex) + { + LogError("添加缓存用户信息异常:" + ex); + } } return _credentialCache; } - + /// + /// 此处是回调信息,如果不回调就重新注册 + /// + /// private void ReceiveData(IAsyncResult asyncResult) { try { + //最新回调反馈时间 + newDataTime = DateTime.Now; + RequestState myRequestState = (RequestState)asyncResult.AsyncState; Stream responseStream = myRequestState.streamResponse; int read = responseStream.EndRead(asyncResult); @@ -754,16 +835,16 @@ namespace WinFormsAppVisitorDeploy if (myRequestState.processLongLinkData != null) { string a = System.Text.Encoding.UTF8.GetString(myRequestState.BufferRead).TrimEnd('\0'); - text(a); - text("*********************"); - WriteLog(a); + AppendShowMsg(a); + AppendShowMsg("*********************"); + LogInfo(a); Byte[] pBuf = new Byte[read]; Array.Copy(myRequestState.BufferRead, pBuf, read); //分包 List list = SplitPackage(pBuf); - int flagindex = 0; + //int flagindex = 0; //遍历包 for (int i = 0; i < list.Count; i++) @@ -790,51 +871,44 @@ namespace WinFormsAppVisitorDeploy } } - catch (WebException e) - { - WriteLog(e.Message); - text("ReceiveData:"+e.Message); - } - catch (IOException e) + catch (Exception ex) { - WriteLog("ReceiveDataError:" + e.Message); - text("ReceiveData:" + e.Message); - //Reconnection(); + LogError("ReceiveData方法执行异常:" + ex); + AppendShowMsg("ReceiveData方法执行异常:" + ex); } } - private void Reconnection() - { - //if (!ret.IsCompleted) - //{ - Thread.Sleep(1000 * 60); - StartEventLongHttp(); - //} - } - + /// + /// 保存图片 + /// + /// + /// private void SaveImage(string countid, Byte[] data) { - string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); - WriteLog(bodyText); - byte[] picBytes = data; - - //抓拍图片 - string strPic = ""; - if (picBytes.Length > 0) + try { - //string path = null; - //string szInfo = "VisibleLightPic"; - //Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); - //string filepath = "D:/Picture/ACSO/" + DateTime.Now.ToString("d"); - //if (Directory.Exists(filepath) == false)//如果不存在就创建file文件夹 - //{ - // Directory.CreateDirectory(filepath); - //} - - //path = string.Format(@"{0}/ACS_LocalTime{1}_{2}.jpeg", filepath, szInfo, rand.Next()); - - //using (FileStream fs = new FileStream(path, FileMode.Create)) - //{ + + string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); + LogInfo(bodyText); + byte[] picBytes = data; + + //抓拍图片 + string strPic = ""; + if (picBytes.Length > 0) + { + //string path = null; + //string szInfo = "VisibleLightPic"; + //Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); + //string filepath = "D:/Picture/ACSO/" + DateTime.Now.ToString("d"); + //if (Directory.Exists(filepath) == false)//如果不存在就创建file文件夹 + //{ + // Directory.CreateDirectory(filepath); + //} + + //path = string.Format(@"{0}/ACS_LocalTime{1}_{2}.jpeg", filepath, szInfo, rand.Next()); + + //using (FileStream fs = new FileStream(path, FileMode.Create)) + //{ int iLen = (int)picBytes.Length; byte[] by = new byte[iLen]; Array.Copy(picBytes, by, picBytes.Length); @@ -843,29 +917,35 @@ namespace WinFormsAppVisitorDeploy //fs.Close(); strPic = Convert.ToBase64String(by); - //} - visitorModel visitormodel = new visitorModel(); - visitormodel.deviceSericeNo = deviceSericeNo; //标识设备号 - visitormodel.VisitorEvent.visitorImage.resourcesContent = countid; - visitormodel.VisitorEvent.visitorImage.resourcesImage = strPic; - - - visitormodel.contentType = "image"; - string requestURI = strUrl; - string requestMethod = "POST"; - string json = JsonConvert.SerializeObject(visitormodel); - //将数据发送给网络服务 - string flag = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" - - - //发送给下发服务 - string requestURI2 = DistributeUserUrl; - string requestMethod2 = "POST"; - string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name - + "\",\"rightPlan\":\"1\",\"imgData\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesImage + "\",\"type\":\"1\",\"controltype\":\"add\"}"; - string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" - WriteLog("SaveImage_发送给下发服务_发送JSON:" + flag2); - WriteLog("SaveImage_发送给网络服务_发送图片:" + flag); + //} + visitorModel visitormodel = new visitorModel(); + visitormodel.deviceSericeNo = deviceSericeNo; //标识设备号 + visitormodel.VisitorEvent.visitorImage.resourcesContent = countid; + visitormodel.VisitorEvent.visitorImage.resourcesImage = strPic; + + + visitormodel.contentType = "image"; + string requestURI = strUrl; + string requestMethod = "POST"; + string json = JsonConvert.SerializeObject(visitormodel); + //将数据发送给网络服务 + string flag = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" + + + //发送给下发服务 + string requestURI2 = DistributeUserUrl; + string requestMethod2 = "POST"; + string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name + + "\",\"rightPlan\":\"1\",\"imgData\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesImage + "\",\"type\":\"1\",\"controltype\":\"add\"}"; + string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" + LogInfo("SaveImage_发送给下发服务_发送JSON:" + flag2); + LogInfo("SaveImage_发送给网络服务_发送图片:" + flag); + } + } + catch (Exception ex) + { + AppendShowMsg("保存图片异常:" + ex); + LogError("保存图片异常:" + ex); } } @@ -876,7 +956,7 @@ namespace WinFormsAppVisitorDeploy try { string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); - WriteLog(bodyText); + LogInfo(bodyText); visitorModel visitormodel = new visitorModel(); visitormodel = JsonConvert.DeserializeObject(bodyText); if (visitormodel == null) @@ -904,10 +984,12 @@ namespace WinFormsAppVisitorDeploy string strparam = JsonConvert.SerializeObject(visitorEventConfirmJSON); string strResponse = string.Empty; - request = (HttpWebRequest)HttpWebRequest.Create(strUrl); + var request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Method = strHttpMethod; + reqList.Add(request); + //获取 WebClient client = new WebClient(); client.Credentials = new NetworkCredential(strUserName, strPassword); @@ -928,7 +1010,7 @@ namespace WinFormsAppVisitorDeploy string json = JsonConvert.SerializeObject(visitormodel); //将数据发送给网络服务 string flag1 = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" - WriteLog("ConfirmEvent_发送给网络服务_发送JSON:" + flag1); + LogInfo("ConfirmEvent_发送给网络服务_发送JSON:" + flag1); string controltype = ""; if (visitormodel.VisitorEvent.registerStatus == "registered") @@ -946,48 +1028,16 @@ namespace WinFormsAppVisitorDeploy string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name + "\",\"rightPlan\":\"1\",\"imgData\":\"\",\"type\":\"0\",\"controltype\":\"" + controltype + "\"}"; string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" - WriteLog("ConfirmEvent_发送给下发服务_发送JSON:" + flag2); + LogInfo("ConfirmEvent_发送给下发服务_发送JSON:" + flag2); } else if (visitormodel.eventType == "VisitorInfoSearchEvent") { - //string searchid = visitormodel.VisitorInfoSearchEvent.searchID; - - //VisirtorInfoSearchEventConfirmInfo visirtorInfoSearchEventConfirmInfo = new VisirtorInfoSearchEventConfirmInfo(); - //visirtorInfoSearchEventConfirmInfo.visitorInfoSearchEventConfirm.searchID = searchid; - //visirtorInfoSearchEventConfirmInfo.visitorInfoSearchEventConfirm.responseStatusStrg = "NO MATCH"; - //visirtorInfoSearchEventConfirmInfo.visitorInfoSearchEventConfirm.numOfMatches = 0; - //visirtorInfoSearchEventConfirmInfo.visitorInfoSearchEventConfirm.totalMatches = 0; - - - - //string strHttpMethod = "PUT"; - //string strUrl = "http://" + strDeviceIp + ":" + sPort + "/ISAPI/AccessControl/visitorInfoSearchEventConfirm"; - - - //string strResponse = string.Empty; - - //request = (HttpWebRequest)HttpWebRequest.Create(strUrl); - //request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); - //request.Method = strHttpMethod; - - ////获取 - //WebClient client = new WebClient(); - //client.Credentials = new NetworkCredential(strUserName, strPassword); - //client.BaseAddress = "http://" + strDeviceIp; - //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); - //client.Headers.Add("ContentLength", strResponse); - - //string str = JsonConvert.SerializeObject(visirtorInfoSearchEventConfirmInfo); - //byte[] bytes = Encoding.UTF8.GetBytes(str); - //byte[] responseData = client.UploadData(strUrl, "PUT", bytes); - - ////string ss = System.Text.Encoding.UTF8.GetString(responseData); - } } catch (Exception e) { - text("ConfirmEvent:" + e.Message); + AppendShowMsg("ConfirmEvent方法执行异常:" + e); + LogError("ConfirmEvent方法执行异常:" + e); } } @@ -1025,10 +1075,12 @@ namespace WinFormsAppVisitorDeploy string strparam = "{\"VisitorAdvanceParamCfg\": {\"autoSyncInfoEnabled\": false,\"autoSyncInfoTimeInterval\": 10,\"visitorAppointEnabled\": false,\"currentEventConfirmEnabled\": false}}"; string strResponse = string.Empty; - request = (HttpWebRequest)HttpWebRequest.Create(strUrl); + var request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Method = strHttpMethod; + reqList.Add(request); + //获取 WebClient client = new WebClient(); client.Credentials = new NetworkCredential(strUserName, strPassword); @@ -1042,46 +1094,67 @@ namespace WinFormsAppVisitorDeploy return; } - catch (WebException e) + catch (Exception e) { - myRequestState.eStatus = e; - WriteLog("RespCallbackError:" + e.Message); - text("RespCallbackError:" + e.Message); + // myRequestState.eStatus = e; + LogError("RespCallback方法执行异常:" + e); + AppendShowMsg("RespCallback方法执行异常:" + e); //***Reconnection(); } } + List reqList = new List(); + bool isOne = true; + public int StartHttpLongLink(string strUserName, string strPassword, string strUrl, string strHttpMethod , string strparam, ProcessLongLinkData processLongLinkData, ref string strResponse, bool bBlock = true) { - - request = (HttpWebRequest)HttpWebRequest.Create(strUrl); - request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); - request.Method = strHttpMethod; - request.KeepAlive = true; // *********** - request.ProtocolVersion = HttpVersion.Version11;//*************** - - - - if (!string.IsNullOrEmpty(strparam)) + try { - byte[] bs = Encoding.ASCII.GetBytes(strparam); - request.ContentType = "application/x-www-form-urlencoded"; - //request.ContentType = "application/xml"; + //验证是否需要断开连接重新初始化 + if (isOne) + { + isOne = false; + //遍历断开所有缓存连接 + for (int i = 0; i < reqList.Count; i++) + { + try + { + reqList[i].Abort(); + } + catch (Exception ex) + { + LogError("重连处理中断开连接异常" + ex); + } + } + reqList.Clear(); + } +; + HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl); + request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); + request.Method = strHttpMethod; + request.KeepAlive = true; // *********** + request.ProtocolVersion = HttpVersion.Version11;//*************** + + reqList.Add(request); - request.ContentLength = bs.Length; - using (Stream reqStream = request.GetRequestStream()) + if (!string.IsNullOrEmpty(strparam)) { - reqStream.Write(bs, 0, bs.Length); + byte[] bs = Encoding.ASCII.GetBytes(strparam); + request.ContentType = "application/x-www-form-urlencoded"; + //request.ContentType = "application/xml"; + + request.ContentLength = bs.Length; + using (Stream reqStream = request.GetRequestStream()) + { + reqStream.Write(bs, 0, bs.Length); + } } - } - try - { RequestState myRequestState = new RequestState(); myRequestState.request = request; myRequestState.processLongLinkData = processLongLinkData; - ret = request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); + var ret = request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); if (bBlock) { @@ -1111,8 +1184,8 @@ namespace WinFormsAppVisitorDeploy Stream st = myRequestState.eStatus.Response.GetResponseStream(); StreamReader sr = new StreamReader(st, System.Text.Encoding.Default); strResponse = sr.ReadToEnd(); - this.textBox1.Text += strResponse.ToString(); - WriteLog(strResponse); + AppendShowMsg(strResponse.ToString()); + LogInfo(strResponse); sr.Close(); st.Close(); return (int)HttpStatus.HttpOther; @@ -1120,30 +1193,30 @@ namespace WinFormsAppVisitorDeploy else { strResponse = myRequestState.eStatus.Status.ToString(); - this.textBox1.Text += strResponse.ToString(); - WriteLog(strResponse); + AppendShowMsg(strResponse.ToString()); + LogInfo(strResponse); return (int)HttpStatus.HttpTimeOut; } } - this.textBox1.Text += HttpStatus.HttpOther.ToString(); - WriteLog(HttpStatus.HttpOther.ToString()); + AppendShowMsg(HttpStatus.HttpOther.ToString()); + LogInfo(HttpStatus.HttpOther.ToString()); return (int)HttpStatus.HttpOther; } } else { - this.textBox1.Text += HttpStatus.HttpOther.ToString(); - WriteLog(HttpStatus.HttpOther.ToString()); + AppendShowMsg(HttpStatus.HttpOther.ToString()); + LogInfo(HttpStatus.HttpOther.ToString()); return (int)HttpStatus.Http200; } } catch (WebException ex) { WebResponse wr = ex.Response; - this.textBox1.Text += ex.Message; - WriteLog(ex.Message); - text("StartHttpLongLink:" + ex.Message); + AppendShowMsg(ex.Message); + LogError(ex.Message); + AppendShowMsg("StartHttpLongLink:" + ex.Message); if (wr != null) { return (int)HttpStatus.HttpOther; @@ -1153,34 +1226,39 @@ namespace WinFormsAppVisitorDeploy return (int)HttpStatus.HttpTimeOut; } } - } - - - private void WriteLog(string msg) - { - string path = AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.ToString("yyyyMM") + "\\"; - string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt"; - - if (Directory.Exists(path) == false)//如果不存在就创建文件夹 - { - Directory.CreateDirectory(path); - } - FileInfo file = new FileInfo(path + filename); - if (!file.Exists) + catch (Exception exc) { - FileStream fs; - fs = File.Create(path + filename); - fs.Close(); + AppendShowMsg("StartHttpLongLink方法执行异常:" + exc); + LogError("StartHttpLongLink方法执行异常:" + exc); + return 99; } + } - using (FileStream fs = new FileStream(path + filename, FileMode.Append, FileAccess.Write)) - { - using (StreamWriter sw = new StreamWriter(fs)) - { - sw.WriteLine("时间:" + DateTime.Now.ToString() + " 信息:" + msg); - } - } + /// + /// 记录普通信息 + /// + /// + private void LogInfo(string msg) + { + MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Info, path = "Info" }); + } + /// + /// 记录错误信息 + /// + /// + private void LogError(string msg) + { + MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Error, path = "Error" }); } + /// + /// 记录调试信息 + /// + /// + private void LogDebug(string msg) + { + MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Error, path = "Error" }); + } + public string SendHttpRequest(string requestURI, string requestMethod, string json) { @@ -1221,10 +1299,20 @@ namespace WinFormsAppVisitorDeploy catch (Exception e) { ReqResult = e.Message; - text("SendHttpRequest:" + e.Message); + AppendShowMsg("SendHttpRequest:" + e.Message); } return ReqResult; } + /// + /// 窗体关闭事件 + /// + /// + /// + private void Form1_FormClosing(object sender, FormClosingEventArgs e) + { + try { System.Environment.Exit(1); } catch (Exception ex) { LogError("强制退出1异常:" + ex); } + try { System.Environment.Exit(0); } catch (Exception ex) { LogError("强制退出0异常:" + ex); } + } } } diff --git a/WinFormsAppVisitorDeploy/MyLogHelper.cs b/WinFormsAppVisitorDeploy/MyLogHelper.cs new file mode 100644 index 0000000..c66687f --- /dev/null +++ b/WinFormsAppVisitorDeploy/MyLogHelper.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinFormsAppVisitorDeploy +{ + + + /// + /// 日志记录帮助类 + /// + public class MyLogHelper + { + + /// + /// 读取配置信息是否记录调试信息:1、不记录;其他、记录 + /// + public static string MyLogDebug = System.Configuration.ConfigurationManager.AppSettings["MyLogDebug"] + ""; + + /// + /// 正常消息队列 + /// + private static ConcurrentQueue infoMsgQueue = new ConcurrentQueue(); + /// + /// 调试消息队列 + /// + private static ConcurrentQueue debugMsgQueue = new ConcurrentQueue(); + /// + /// 错误消息队列 + /// + private static ConcurrentQueue errorMsgQueue = new ConcurrentQueue(); + /// + /// 控制文件写入线程 + /// + private static Task logTask; + /// + /// 记录信息 + /// + /// + public static void WriteMsg(LogInfoMo infoObj) + { + try + { + if (infoObj != null) + { + switch (infoObj.msgType) + { + case EnumLogMsgTypeEnum.Info: + infoMsgQueue.Enqueue(infoObj); + break; + case EnumLogMsgTypeEnum.Debug: + if (MyLogDebug == "1") + { + //不记录调试信息 + } + else + { + debugMsgQueue.Enqueue(infoObj); + } + break; + case EnumLogMsgTypeEnum.Error: + errorMsgQueue.Enqueue(infoObj); + break; + } + WriteExecute(); + } + } + catch (Exception ex) + { + infoObj.message = "队列异常:" + ex; + errorMsgQueue.Enqueue(infoObj); + } + } + /// + /// 执行文件写入 + /// + private static void WriteExecute() + { + try + { + //判断线程是否创建 + if (logTask == null) + { + logTask = Task.Factory.StartNew(async () => + { + while (true) + { + //判断是否退出线程 + if (MyTaskControlHelper.TokenSource.IsCancellationRequested) + { + return; + } + // 初始化为true时执行WaitOne不阻塞 + MyTaskControlHelper.ResetEvent.WaitOne(); + + // 模拟等待1ms + await Task.Delay(1); + + //正常信息写入文件 + try + { + if (infoMsgQueue.TryDequeue(out LogInfoMo infoObj)) + { + WriteFire(infoObj); + } + } + catch (Exception ex) + { + string str = "普通信息队列处理异常:" + ex; + errorMsgQueue.Enqueue(new LogInfoMo() { message = str, msgType = EnumLogMsgTypeEnum.Error }); + } + + //错误信息写入文件 + try + { + if (errorMsgQueue.TryDequeue(out LogInfoMo infoObj)) + { + WriteFire(infoObj); + } + } + catch (Exception ex) + { + string str = "错误信息队列处理异常:" + ex; + errorMsgQueue.Enqueue(new LogInfoMo() { message = str, msgType = EnumLogMsgTypeEnum.Error }); + } + + //调试信息写入文件 + try + { + if (debugMsgQueue.TryDequeue(out LogInfoMo infoObj)) + { + WriteFire(infoObj); + } + } + catch (Exception ex) + { + string str = "调试信息队列处理异常:" + ex; + errorMsgQueue.Enqueue(new LogInfoMo() { message = str, msgType = EnumLogMsgTypeEnum.Error }); + } + + } + }); + } + + } + catch (Exception ex) + { + string str = "文件队列处理异常:" + ex; + errorMsgQueue.Enqueue(new LogInfoMo() { message = str, msgType = EnumLogMsgTypeEnum.Error }); + } + } + /// + /// 将信息写入文件 + /// + /// + /// + private static void WriteFire(LogInfoMo infoObj) + { + try + { + //获取程序所在目录 + string pathStr = AppDomain.CurrentDomain.BaseDirectory + "log\\" + (string.IsNullOrEmpty(infoObj.path) ? "" : infoObj.path + "\\") + + DateTime.Now.Year + "\\" + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\"; + //判断文件夹是否存在 + if (Directory.Exists(pathStr) == false) + { + //不存在文件夹则创建 + Directory.CreateDirectory(pathStr); + } + string firePath = pathStr + infoObj.msgType.ToString() + DateTime.Now.ToString("yyyyMMddHH") + ".txt"; + + using (FileStream fs = new FileStream(firePath, FileMode.Append, FileAccess.Write)) + { + using (StreamWriter sw = new StreamWriter(fs)) + { + string str = DateTime.Now + "\t" + infoObj.message; + sw.WriteLine(str); + } + } + } + catch (Exception ex) + { + string str = DateTime.Now + "\t 文件写入异常:" + ex; + errorMsgQueue.Enqueue(new LogInfoMo() { message = str, msgType = EnumLogMsgTypeEnum.Error }); + } + } + + } + /// + /// 日志信息类型枚举 + /// + public enum EnumLogMsgTypeEnum + { + /// + /// 正常信息 + /// + Info = 0, + /// + /// 错误信息 + /// + Error = 1, + /// + /// 调试信息 + /// + Debug = 2, + } + /// + /// 操作日志记录类型 + /// + public enum EnumOperationLogType + { + //0、查询;1、新增;2、修改;3、删除;4、异常信息;5、其他 + + /// + /// 查询 + /// + Query = 0, + /// + /// 新增 + /// + Add = 1, + /// + /// 更新 + /// + Update = 2, + /// + /// 删除 + /// + Delete = 3, + /// + /// 异常 + /// + Error = 4, + /// + /// 其他 + /// + Other = 5, + } + + /// + /// 记录信息数据模型 + /// + public class LogInfoMo + { + /// + /// 信息保存路径,默认不单独保存 + /// + public string path { get; set; } + /// + /// 记录信息内容字符串 + /// + public string message { get; set; } + /// + /// 信息类型 + /// + public EnumLogMsgTypeEnum msgType { get; set; } + } +} diff --git a/WinFormsAppVisitorDeploy/MyTaskControlHelper.cs b/WinFormsAppVisitorDeploy/MyTaskControlHelper.cs new file mode 100644 index 0000000..1081d44 --- /dev/null +++ b/WinFormsAppVisitorDeploy/MyTaskControlHelper.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace WinFormsAppVisitorDeploy +{ + /// + /// Task线程统一控制帮助类 + /// + public class MyTaskControlHelper + { + /// + /// 控制Task是否退出 + /// + private static CancellationTokenSource tokenSource; + + /// + /// 控制Task是否暂停 + /// + private static ManualResetEvent resetEvent = new ManualResetEvent(true); + + /// + /// 获取Task退出控制器 + /// + public static CancellationTokenSource TokenSource + { + get + { + if (tokenSource == null) + { + tokenSource = new CancellationTokenSource(); + } + return tokenSource; + } + } + /// + /// 获取Task暂停控制器 + /// + public static ManualResetEvent ResetEvent { get { return resetEvent; } } + + } +} diff --git a/WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj b/WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj index 9f936dd..29dc674 100644 --- a/WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj +++ b/WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj @@ -58,6 +58,8 @@ Form1.cs + +