Browse Source

修改代码

master
王瑞 2 years ago
parent
commit
9a63db0061
  1. BIN
      WinFormsAppVisitorDeploy/.vs/WinFormsAppVisitorDeploy/v16/.suo
  2. 4
      WinFormsAppVisitorDeploy/App.config
  3. 26
      WinFormsAppVisitorDeploy/Form1.Designer.cs
  4. 600
      WinFormsAppVisitorDeploy/Form1.cs
  5. 262
      WinFormsAppVisitorDeploy/MyLogHelper.cs
  6. 45
      WinFormsAppVisitorDeploy/MyTaskControlHelper.cs
  7. 2
      WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj

BIN
WinFormsAppVisitorDeploy/.vs/WinFormsAppVisitorDeploy/v16/.suo

Binary file not shown.

4
WinFormsAppVisitorDeploy/App.config

@ -3,7 +3,9 @@
<connectionStrings> <connectionStrings>
</connectionStrings> </connectionStrings>
<appSettings> <appSettings>
<add key="strDeviceIp" value="192.168.1.170"/> <!--访客机服务器IP地址-->
<add key="strDeviceIp" value="192.168.31.210"/>
<!--访客机服务对接接口-->
<add key="sPort" value="81"/> <add key="sPort" value="81"/>
<add key="strUserName" value="admin"/> <add key="strUserName" value="admin"/>
<add key="strPassword" value="admin123"/> <add key="strPassword" value="admin123"/>

26
WinFormsAppVisitorDeploy/Form1.Designer.cs

@ -30,7 +30,7 @@ namespace WinFormsAppVisitorDeploy
private void InitializeComponent() private void InitializeComponent()
{ {
this.button1 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox(); this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout(); this.SuspendLayout();
// //
// button1 // button1
@ -44,37 +44,37 @@ namespace WinFormsAppVisitorDeploy
this.button1.UseVisualStyleBackColor = true; this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click); this.button1.Click += new System.EventHandler(this.button1_Click);
// //
// textBox1 // richTextBox1
// //
this.textBox1.Location = new System.Drawing.Point(10, 37); this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
this.textBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); | System.Windows.Forms.AnchorStyles.Left)
this.textBox1.MaxLength = 327670; | System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Multiline = true; this.richTextBox1.Location = new System.Drawing.Point(10, 38);
this.textBox1.Name = "textBox1"; this.richTextBox1.Name = "richTextBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.richTextBox1.Size = new System.Drawing.Size(664, 403);
this.textBox1.Size = new System.Drawing.Size(666, 392); this.richTextBox1.TabIndex = 1;
this.textBox1.TabIndex = 1; this.richTextBox1.Text = "";
// //
// Form1 // Form1
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(686, 453); this.ClientSize = new System.Drawing.Size(686, 453);
this.Controls.Add(this.textBox1); this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.button1); this.Controls.Add(this.button1);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "Form1"; this.Name = "Form1";
this.Text = "Form1"; this.Text = "Form1";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load); this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout();
} }
#endregion #endregion
private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.RichTextBox richTextBox1;
} }
} }

600
WinFormsAppVisitorDeploy/Form1.cs

@ -19,38 +19,69 @@ namespace WinFormsAppVisitorDeploy
InitializeComponent(); InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; Control.CheckForIllegalCrossThreadCalls = false;
} }
/// <summary>
public void Form1_Load(object sender,EventArgs e) /// 窗口初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Form1_Load(object sender, EventArgs e)
{ {
StartEventLongHttp(); StartEventLongHttp();
//开个线程 //开个线程
{ {
Thread T = new Thread(Test); Thread T = new Thread(ThreadFunction);
//启动新的线程 //启动新的线程
T.Start(); T.Start();
} }
} }
public void Test() /// <summary>
/// 定时验证是否收到心跳信息
/// </summary>
public void ThreadFunction()
{ {
while(true) while (true)
{ {
Thread.Sleep(20000); Thread.Sleep(10000);
TimeSpan ts = DateTime.Now - a; //计算时间差 TimeSpan ts = DateTime.Now - newDataTime; //计算时间差
string time = ts.TotalSeconds.ToString(); //将时间差转换为秒 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(); StartEventLongHttp();
AppendShowMsg("心跳超时,重新连接执行结束");
LogError("心跳超时,重新连接执行结束");
}
else
{
//心跳未超时
AppendShowMsg("心跳正常收到数据," + timLen + "秒");
LogDebug("心跳正常收到数据," + timLen + "秒");
} }
} }
} }
/// <summary>
/// 最新收到信息时间
/// </summary>
DateTime newDataTime = DateTime.Now;
DateTime a = DateTime.Now; /// <summary>
/// 访客机服务器IP地址
/// </summary>
string strDeviceIp = ConfigurationManager.AppSettings["strDeviceIp"].ToString(); string strDeviceIp = ConfigurationManager.AppSettings["strDeviceIp"].ToString();
/// <summary>
/// 访客机服务对接接口
/// </summary>
string sPort = ConfigurationManager.AppSettings["sPort"].ToString(); string sPort = ConfigurationManager.AppSettings["sPort"].ToString();
string strUserName = ConfigurationManager.AppSettings["strUserName"].ToString(); string strUserName = ConfigurationManager.AppSettings["strUserName"].ToString();
string strPassword = ConfigurationManager.AppSettings["strPassword"].ToString(); string strPassword = ConfigurationManager.AppSettings["strPassword"].ToString();
@ -58,7 +89,6 @@ namespace WinFormsAppVisitorDeploy
string DistributeUserUrl = ConfigurationManager.AppSettings["DistributeUserUrl"].ToString(); string DistributeUserUrl = ConfigurationManager.AppSettings["DistributeUserUrl"].ToString();
string strUrl = ConfigurationManager.AppSettings["strUrl"].ToString(); string strUrl = ConfigurationManager.AppSettings["strUrl"].ToString();
IAsyncResult ret;
public class visitorModel public class visitorModel
{ {
public string deviceSericeNo { get; set; } public string deviceSericeNo { get; set; }
@ -162,10 +192,15 @@ namespace WinFormsAppVisitorDeploy
public int totalMatches { get; set; } public int totalMatches { get; set; }
} }
/// <summary>
/// 手动初始化操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e) private void button1_Click(object sender, EventArgs e)
{ {
isOne = true;
StartEventLongHttp(); StartEventLongHttp();
} }
@ -186,14 +221,33 @@ namespace WinFormsAppVisitorDeploy
HttpOther, HttpOther,
HttpTimeOut HttpTimeOut
} }
/// <summary>
public void text(string info) /// 添加显示信息
/// </summary>
/// <param name="info"></param>
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 public class RequestState
{ {
@ -241,45 +295,49 @@ namespace WinFormsAppVisitorDeploy
//private IDeviceTree m_deviceTree = null; //private IDeviceTree m_deviceTree = null;
public class CSubscribeDeviceMgmt
{
public CSubscribeDeviceMgmt()
{
SubscribeDeviceMgmt = new CSubscribeDeviceMgmtInter();
}
public class CSubscribeDeviceMgmtInter
{
public CSubscribeDeviceMgmtInter()
{
DevEventList = new List<CDevEventListItem>();
}
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<CDevEventListItem> DevEventList { get; set; }
} ////不知道干嘛用的一段
public CSubscribeDeviceMgmtInter SubscribeDeviceMgmt { get; set; } //public class CSubscribeDeviceMgmt
} //{
// public CSubscribeDeviceMgmt()
// {
// SubscribeDeviceMgmt = new CSubscribeDeviceMgmtInter();
// }
// public class CSubscribeDeviceMgmtInter
// {
// public CSubscribeDeviceMgmtInter()
// {
// DevEventList = new List<CDevEventListItem>();
// }
// 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<CDevEventListItem> DevEventList { get; set; }
// }
// public CSubscribeDeviceMgmtInter SubscribeDeviceMgmt { get; set; }
//}
/// <summary>
/// 开始执行接收访客机登记信息
/// </summary>
/// <returns></returns>
public int StartEventLongHttp() public int StartEventLongHttp()
{ {
a = DateTime.Now;
string strparam = ""; string strparam = "";
string strHttpMethod = "GET"; string strHttpMethod = "GET";
@ -302,6 +360,7 @@ namespace WinFormsAppVisitorDeploy
return iRet; return iRet;
} }
/// <summary>
/// 匹配相同的子byte数组 /// 匹配相同的子byte数组
/// </summary> /// </summary>
/// <param name="src">目标byte序列</param> /// <param name="src">目标byte序列</param>
@ -310,39 +369,46 @@ namespace WinFormsAppVisitorDeploy
/// <returns>参数错误或未匹配到返回-1,否则返回value在src上出现的位置</returns> /// <returns>参数错误或未匹配到返回-1,否则返回value在src上出现的位置</returns>
internal int IndexOf(byte[] src, int index, byte[] value) 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 if (src.Length == 0 || src.Length < index
|| value.Length == 0 || src.Length < value.Length) || 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 (value.Length == 1) return -1;
{ }
return i; for (int i = index; i < src.Length - value.Length; i++)
} {
bool flag = true; if (src[i] == value[0])
for (int j = 1; j < value.Length; j++)
{ {
if (src[i + j] != value[j]) if (value.Length == 1)
{ {
flag = false; return i;
break; }
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; return -1;
} }
@ -350,7 +416,6 @@ namespace WinFormsAppVisitorDeploy
string strdatatime = ""; string strdatatime = "";
int piccount = 0; int piccount = 0;
HttpWebRequest request;
public class CHeartBeat public class CHeartBeat
{ {
@ -591,9 +656,10 @@ namespace WinFormsAppVisitorDeploy
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("ParseAlarmData Exception raised!"); AppendShowMsg("ParseAlarmData方法执行异常:" + e.Message);
Console.WriteLine("\nMessage:{0}", e.Message);
text("ParseAlarmData:" + e.Message); LogError("ParseAlarmData方法执行异常" + e);
return false; return false;
} }
@ -611,11 +677,12 @@ namespace WinFormsAppVisitorDeploy
//} //}
public class ContantData ////不知道干嘛用的一段
{ //public class ContantData
public string ContentType { get; set; } //{
public byte[] Content { get; set; } // public string ContentType { get; set; }
} // public byte[] Content { get; set; }
//}
public class PackageData 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; int endLength = pBuf.Length - endindex;
@ -720,7 +787,8 @@ namespace WinFormsAppVisitorDeploy
catch (Exception e) catch (Exception e)
{ {
statusString = httpBody; statusString = httpBody;
text("ParserResponseStatus:" + e.Message); AppendShowMsg("ParserResponseStatus方法执行异常:" + e.Message);
LogDebug("ParserResponseStatus方法执行异常:" + e);
} }
return 0; return 0;
} }
@ -735,17 +803,30 @@ namespace WinFormsAppVisitorDeploy
} }
if (strURL != sUrl) if (strURL != sUrl)
{ {
_credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword)); try
strURL = sUrl; {
_credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword));
strURL = sUrl;
}
catch (Exception ex)
{
LogError("添加缓存用户信息异常:" + ex);
}
} }
return _credentialCache; return _credentialCache;
} }
/// <summary>
/// 此处是回调信息,如果不回调就重新注册
/// </summary>
/// <param name="asyncResult"></param>
private void ReceiveData(IAsyncResult asyncResult) private void ReceiveData(IAsyncResult asyncResult)
{ {
try try
{ {
//最新回调反馈时间
newDataTime = DateTime.Now;
RequestState myRequestState = (RequestState)asyncResult.AsyncState; RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.streamResponse; Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead(asyncResult); int read = responseStream.EndRead(asyncResult);
@ -754,16 +835,16 @@ namespace WinFormsAppVisitorDeploy
if (myRequestState.processLongLinkData != null) if (myRequestState.processLongLinkData != null)
{ {
string a = System.Text.Encoding.UTF8.GetString(myRequestState.BufferRead).TrimEnd('\0'); string a = System.Text.Encoding.UTF8.GetString(myRequestState.BufferRead).TrimEnd('\0');
text(a); AppendShowMsg(a);
text("*********************"); AppendShowMsg("*********************");
WriteLog(a); LogInfo(a);
Byte[] pBuf = new Byte[read]; Byte[] pBuf = new Byte[read];
Array.Copy(myRequestState.BufferRead, pBuf, read); Array.Copy(myRequestState.BufferRead, pBuf, read);
//分包 //分包
List<PackageData> list = SplitPackage(pBuf); List<PackageData> list = SplitPackage(pBuf);
int flagindex = 0; //int flagindex = 0;
//遍历包 //遍历包
for (int i = 0; i < list.Count; i++) for (int i = 0; i < list.Count; i++)
@ -790,51 +871,44 @@ namespace WinFormsAppVisitorDeploy
} }
} }
catch (WebException e) catch (Exception ex)
{
WriteLog(e.Message);
text("ReceiveData:"+e.Message);
}
catch (IOException e)
{ {
WriteLog("ReceiveDataError:" + e.Message); LogError("ReceiveData方法执行异常:" + ex);
text("ReceiveData:" + e.Message); AppendShowMsg("ReceiveData方法执行异常:" + ex);
//Reconnection();
} }
} }
private void Reconnection() /// <summary>
{ /// 保存图片
//if (!ret.IsCompleted) /// </summary>
//{ /// <param name="countid"></param>
Thread.Sleep(1000 * 60); /// <param name="data"></param>
StartEventLongHttp();
//}
}
private void SaveImage(string countid, Byte[] data) private void SaveImage(string countid, Byte[] data)
{ {
string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); try
WriteLog(bodyText);
byte[] picBytes = data;
//抓拍图片
string strPic = "";
if (picBytes.Length > 0)
{ {
//string path = null;
//string szInfo = "VisibleLightPic"; string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0');
//Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); LogInfo(bodyText);
//string filepath = "D:/Picture/ACSO/" + DateTime.Now.ToString("d"); byte[] picBytes = data;
//if (Directory.Exists(filepath) == false)//如果不存在就创建file文件夹
//{ //抓拍图片
// Directory.CreateDirectory(filepath); string strPic = "";
//} if (picBytes.Length > 0)
{
//path = string.Format(@"{0}/ACS_LocalTime{1}_{2}.jpeg", filepath, szInfo, rand.Next()); //string path = null;
//string szInfo = "VisibleLightPic";
//using (FileStream fs = new FileStream(path, FileMode.Create)) //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; int iLen = (int)picBytes.Length;
byte[] by = new byte[iLen]; byte[] by = new byte[iLen];
Array.Copy(picBytes, by, picBytes.Length); Array.Copy(picBytes, by, picBytes.Length);
@ -843,29 +917,35 @@ namespace WinFormsAppVisitorDeploy
//fs.Close(); //fs.Close();
strPic = Convert.ToBase64String(by); strPic = Convert.ToBase64String(by);
//} //}
visitorModel visitormodel = new visitorModel(); visitorModel visitormodel = new visitorModel();
visitormodel.deviceSericeNo = deviceSericeNo; //标识设备号 visitormodel.deviceSericeNo = deviceSericeNo; //标识设备号
visitormodel.VisitorEvent.visitorImage.resourcesContent = countid; visitormodel.VisitorEvent.visitorImage.resourcesContent = countid;
visitormodel.VisitorEvent.visitorImage.resourcesImage = strPic; visitormodel.VisitorEvent.visitorImage.resourcesImage = strPic;
visitormodel.contentType = "image"; visitormodel.contentType = "image";
string requestURI = strUrl; string requestURI = strUrl;
string requestMethod = "POST"; string requestMethod = "POST";
string json = JsonConvert.SerializeObject(visitormodel); string json = JsonConvert.SerializeObject(visitormodel);
//将数据发送给网络服务 //将数据发送给网络服务
string flag = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" string flag = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false"
//发送给下发服务 //发送给下发服务
string requestURI2 = DistributeUserUrl; string requestURI2 = DistributeUserUrl;
string requestMethod2 = "POST"; string requestMethod2 = "POST";
string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name 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\"}"; + "\",\"rightPlan\":\"1\",\"imgData\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesImage + "\",\"type\":\"1\",\"controltype\":\"add\"}";
string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false"
WriteLog("SaveImage_发送给下发服务_发送JSON:" + flag2); LogInfo("SaveImage_发送给下发服务_发送JSON:" + flag2);
WriteLog("SaveImage_发送给网络服务_发送图片:" + flag); LogInfo("SaveImage_发送给网络服务_发送图片:" + flag);
}
}
catch (Exception ex)
{
AppendShowMsg("保存图片异常:" + ex);
LogError("保存图片异常:" + ex);
} }
} }
@ -876,7 +956,7 @@ namespace WinFormsAppVisitorDeploy
try try
{ {
string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0');
WriteLog(bodyText); LogInfo(bodyText);
visitorModel visitormodel = new visitorModel(); visitorModel visitormodel = new visitorModel();
visitormodel = JsonConvert.DeserializeObject<visitorModel>(bodyText); visitormodel = JsonConvert.DeserializeObject<visitorModel>(bodyText);
if (visitormodel == null) if (visitormodel == null)
@ -904,10 +984,12 @@ namespace WinFormsAppVisitorDeploy
string strparam = JsonConvert.SerializeObject(visitorEventConfirmJSON); string strparam = JsonConvert.SerializeObject(visitorEventConfirmJSON);
string strResponse = string.Empty; string strResponse = string.Empty;
request = (HttpWebRequest)HttpWebRequest.Create(strUrl); var request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword);
request.Method = strHttpMethod; request.Method = strHttpMethod;
reqList.Add(request);
//获取 //获取
WebClient client = new WebClient(); WebClient client = new WebClient();
client.Credentials = new NetworkCredential(strUserName, strPassword); client.Credentials = new NetworkCredential(strUserName, strPassword);
@ -928,7 +1010,7 @@ namespace WinFormsAppVisitorDeploy
string json = JsonConvert.SerializeObject(visitormodel); string json = JsonConvert.SerializeObject(visitormodel);
//将数据发送给网络服务 //将数据发送给网络服务
string flag1 = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" string flag1 = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false"
WriteLog("ConfirmEvent_发送给网络服务_发送JSON:" + flag1); LogInfo("ConfirmEvent_发送给网络服务_发送JSON:" + flag1);
string controltype = ""; string controltype = "";
if (visitormodel.VisitorEvent.registerStatus == "registered") 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 string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name
+ "\",\"rightPlan\":\"1\",\"imgData\":\"\",\"type\":\"0\",\"controltype\":\"" + controltype + "\"}"; + "\",\"rightPlan\":\"1\",\"imgData\":\"\",\"type\":\"0\",\"controltype\":\"" + controltype + "\"}";
string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false"
WriteLog("ConfirmEvent_发送给下发服务_发送JSON:" + flag2); LogInfo("ConfirmEvent_发送给下发服务_发送JSON:" + flag2);
} }
else if (visitormodel.eventType == "VisitorInfoSearchEvent") 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) 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 strparam = "{\"VisitorAdvanceParamCfg\": {\"autoSyncInfoEnabled\": false,\"autoSyncInfoTimeInterval\": 10,\"visitorAppointEnabled\": false,\"currentEventConfirmEnabled\": false}}";
string strResponse = string.Empty; string strResponse = string.Empty;
request = (HttpWebRequest)HttpWebRequest.Create(strUrl); var request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword);
request.Method = strHttpMethod; request.Method = strHttpMethod;
reqList.Add(request);
//获取 //获取
WebClient client = new WebClient(); WebClient client = new WebClient();
client.Credentials = new NetworkCredential(strUserName, strPassword); client.Credentials = new NetworkCredential(strUserName, strPassword);
@ -1042,46 +1094,67 @@ namespace WinFormsAppVisitorDeploy
return; return;
} }
catch (WebException e) catch (Exception e)
{ {
myRequestState.eStatus = e; // myRequestState.eStatus = e;
WriteLog("RespCallbackError:" + e.Message); LogError("RespCallback方法执行异常:" + e);
text("RespCallbackError:" + e.Message); AppendShowMsg("RespCallback方法执行异常:" + e);
//***Reconnection(); //***Reconnection();
} }
} }
List<HttpWebRequest> reqList = new List<HttpWebRequest>();
bool isOne = true;
public int StartHttpLongLink(string strUserName, string strPassword, string strUrl, string strHttpMethod public int StartHttpLongLink(string strUserName, string strPassword, string strUrl, string strHttpMethod
, string strparam, ProcessLongLinkData processLongLinkData, ref string strResponse, bool bBlock = true) , string strparam, ProcessLongLinkData processLongLinkData, ref string strResponse, bool bBlock = true)
{ {
try
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))
{ {
byte[] bs = Encoding.ASCII.GetBytes(strparam); //验证是否需要断开连接重新初始化
request.ContentType = "application/x-www-form-urlencoded"; if (isOne)
//request.ContentType = "application/xml"; {
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; if (!string.IsNullOrEmpty(strparam))
using (Stream reqStream = request.GetRequestStream())
{ {
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(); RequestState myRequestState = new RequestState();
myRequestState.request = request; myRequestState.request = request;
myRequestState.processLongLinkData = processLongLinkData; myRequestState.processLongLinkData = processLongLinkData;
ret = request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); var ret = request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
if (bBlock) if (bBlock)
{ {
@ -1111,8 +1184,8 @@ namespace WinFormsAppVisitorDeploy
Stream st = myRequestState.eStatus.Response.GetResponseStream(); Stream st = myRequestState.eStatus.Response.GetResponseStream();
StreamReader sr = new StreamReader(st, System.Text.Encoding.Default); StreamReader sr = new StreamReader(st, System.Text.Encoding.Default);
strResponse = sr.ReadToEnd(); strResponse = sr.ReadToEnd();
this.textBox1.Text += strResponse.ToString(); AppendShowMsg(strResponse.ToString());
WriteLog(strResponse); LogInfo(strResponse);
sr.Close(); sr.Close();
st.Close(); st.Close();
return (int)HttpStatus.HttpOther; return (int)HttpStatus.HttpOther;
@ -1120,30 +1193,30 @@ namespace WinFormsAppVisitorDeploy
else else
{ {
strResponse = myRequestState.eStatus.Status.ToString(); strResponse = myRequestState.eStatus.Status.ToString();
this.textBox1.Text += strResponse.ToString(); AppendShowMsg(strResponse.ToString());
WriteLog(strResponse); LogInfo(strResponse);
return (int)HttpStatus.HttpTimeOut; return (int)HttpStatus.HttpTimeOut;
} }
} }
this.textBox1.Text += HttpStatus.HttpOther.ToString(); AppendShowMsg(HttpStatus.HttpOther.ToString());
WriteLog(HttpStatus.HttpOther.ToString()); LogInfo(HttpStatus.HttpOther.ToString());
return (int)HttpStatus.HttpOther; return (int)HttpStatus.HttpOther;
} }
} }
else else
{ {
this.textBox1.Text += HttpStatus.HttpOther.ToString(); AppendShowMsg(HttpStatus.HttpOther.ToString());
WriteLog(HttpStatus.HttpOther.ToString()); LogInfo(HttpStatus.HttpOther.ToString());
return (int)HttpStatus.Http200; return (int)HttpStatus.Http200;
} }
} }
catch (WebException ex) catch (WebException ex)
{ {
WebResponse wr = ex.Response; WebResponse wr = ex.Response;
this.textBox1.Text += ex.Message; AppendShowMsg(ex.Message);
WriteLog(ex.Message); LogError(ex.Message);
text("StartHttpLongLink:" + ex.Message); AppendShowMsg("StartHttpLongLink:" + ex.Message);
if (wr != null) if (wr != null)
{ {
return (int)HttpStatus.HttpOther; return (int)HttpStatus.HttpOther;
@ -1153,34 +1226,39 @@ namespace WinFormsAppVisitorDeploy
return (int)HttpStatus.HttpTimeOut; return (int)HttpStatus.HttpTimeOut;
} }
} }
} catch (Exception exc)
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)
{ {
FileStream fs; AppendShowMsg("StartHttpLongLink方法执行异常:" + exc);
fs = File.Create(path + filename); LogError("StartHttpLongLink方法执行异常:" + exc);
fs.Close(); return 99;
} }
}
using (FileStream fs = new FileStream(path + filename, FileMode.Append, FileAccess.Write)) /// <summary>
{ /// 记录普通信息
using (StreamWriter sw = new StreamWriter(fs)) /// </summary>
{ /// <param name="msg"></param>
sw.WriteLine("时间:" + DateTime.Now.ToString() + " 信息:" + msg); private void LogInfo(string msg)
} {
} MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Info, path = "Info" });
}
/// <summary>
/// 记录错误信息
/// </summary>
/// <param name="msg"></param>
private void LogError(string msg)
{
MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Error, path = "Error" });
} }
/// <summary>
/// 记录调试信息
/// </summary>
/// <param name="msg"></param>
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) public string SendHttpRequest(string requestURI, string requestMethod, string json)
{ {
@ -1221,10 +1299,20 @@ namespace WinFormsAppVisitorDeploy
catch (Exception e) catch (Exception e)
{ {
ReqResult = e.Message; ReqResult = e.Message;
text("SendHttpRequest:" + e.Message); AppendShowMsg("SendHttpRequest:" + e.Message);
} }
return ReqResult; return ReqResult;
} }
/// <summary>
/// 窗体关闭事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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); }
}
} }
} }

262
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
{
/// <summary>
/// 日志记录帮助类
/// </summary>
public class MyLogHelper
{
/// <summary>
/// 读取配置信息是否记录调试信息:1、不记录;其他、记录
/// </summary>
public static string MyLogDebug = System.Configuration.ConfigurationManager.AppSettings["MyLogDebug"] + "";
/// <summary>
/// 正常消息队列
/// </summary>
private static ConcurrentQueue<LogInfoMo> infoMsgQueue = new ConcurrentQueue<LogInfoMo>();
/// <summary>
/// 调试消息队列
/// </summary>
private static ConcurrentQueue<LogInfoMo> debugMsgQueue = new ConcurrentQueue<LogInfoMo>();
/// <summary>
/// 错误消息队列
/// </summary>
private static ConcurrentQueue<LogInfoMo> errorMsgQueue = new ConcurrentQueue<LogInfoMo>();
/// <summary>
/// 控制文件写入线程
/// </summary>
private static Task logTask;
/// <summary>
/// 记录信息
/// </summary>
/// <param name="infoObj"></param>
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);
}
}
/// <summary>
/// 执行文件写入
/// </summary>
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 });
}
}
/// <summary>
/// 将信息写入文件
/// </summary>
/// <param name="msgType"></param>
/// <param name="msg"></param>
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 });
}
}
}
/// <summary>
/// 日志信息类型枚举
/// </summary>
public enum EnumLogMsgTypeEnum
{
/// <summary>
/// 正常信息
/// </summary>
Info = 0,
/// <summary>
/// 错误信息
/// </summary>
Error = 1,
/// <summary>
/// 调试信息
/// </summary>
Debug = 2,
}
/// <summary>
/// 操作日志记录类型
/// </summary>
public enum EnumOperationLogType
{
//0、查询;1、新增;2、修改;3、删除;4、异常信息;5、其他
/// <summary>
/// 查询
/// </summary>
Query = 0,
/// <summary>
/// 新增
/// </summary>
Add = 1,
/// <summary>
/// 更新
/// </summary>
Update = 2,
/// <summary>
/// 删除
/// </summary>
Delete = 3,
/// <summary>
/// 异常
/// </summary>
Error = 4,
/// <summary>
/// 其他
/// </summary>
Other = 5,
}
/// <summary>
/// 记录信息数据模型
/// </summary>
public class LogInfoMo
{
/// <summary>
/// 信息保存路径,默认不单独保存
/// </summary>
public string path { get; set; }
/// <summary>
/// 记录信息内容字符串
/// </summary>
public string message { get; set; }
/// <summary>
/// 信息类型
/// </summary>
public EnumLogMsgTypeEnum msgType { get; set; }
}
}

45
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
{
/// <summary>
/// Task线程统一控制帮助类
/// </summary>
public class MyTaskControlHelper
{
/// <summary>
/// 控制Task是否退出
/// </summary>
private static CancellationTokenSource tokenSource;
/// <summary>
/// 控制Task是否暂停
/// </summary>
private static ManualResetEvent resetEvent = new ManualResetEvent(true);
/// <summary>
/// 获取Task退出控制器
/// </summary>
public static CancellationTokenSource TokenSource
{
get
{
if (tokenSource == null)
{
tokenSource = new CancellationTokenSource();
}
return tokenSource;
}
}
/// <summary>
/// 获取Task暂停控制器
/// </summary>
public static ManualResetEvent ResetEvent { get { return resetEvent; } }
}
}

2
WinFormsAppVisitorDeploy/WinFormsAppVisitorDeploy.csproj

@ -58,6 +58,8 @@
<Compile Include="Form1.Designer.cs"> <Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="MyLogHelper.cs" />
<Compile Include="MyTaskControlHelper.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx"> <EmbeddedResource Include="Form1.resx">

Loading…
Cancel
Save