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. 596
      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>
<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="strUserName" value="admin"/>
<add key="strPassword" value="admin123"/>

26
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;
}
}

596
WinFormsAppVisitorDeploy/Form1.cs

@ -19,38 +19,69 @@ namespace WinFormsAppVisitorDeploy
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
public void Form1_Load(object sender,EventArgs e)
/// <summary>
/// 窗口初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Form1_Load(object sender, EventArgs e)
{
StartEventLongHttp();
//开个线程
{
Thread T = new Thread(Test);
Thread T = new Thread(ThreadFunction);
//启动新的线程
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(); //将时间差转换为秒
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 + "秒");
}
}
}
/// <summary>
/// 最新收到信息时间
/// </summary>
DateTime newDataTime = DateTime.Now;
DateTime a = DateTime.Now;
/// <summary>
/// 访客机服务器IP地址
/// </summary>
string strDeviceIp = ConfigurationManager.AppSettings["strDeviceIp"].ToString();
/// <summary>
/// 访客机服务对接接口
/// </summary>
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; }
}
/// <summary>
/// 手动初始化操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
isOne = true;
StartEventLongHttp();
}
@ -186,14 +221,33 @@ namespace WinFormsAppVisitorDeploy
HttpOther,
HttpTimeOut
}
public void text(string info)
/// <summary>
/// 添加显示信息
/// </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
{
@ -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<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()
{
a = DateTime.Now;
string strparam = "";
string strHttpMethod = "GET";
@ -302,6 +360,7 @@ namespace WinFormsAppVisitorDeploy
return iRet;
}
/// <summary>
/// 匹配相同的子byte数组
/// </summary>
/// <param name="src">目标byte序列</param>
@ -310,39 +369,46 @@ namespace WinFormsAppVisitorDeploy
/// <returns>参数错误或未匹配到返回-1,否则返回value在src上出现的位置</returns>
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;
}
/// <summary>
/// 此处是回调信息,如果不回调就重新注册
/// </summary>
/// <param name="asyncResult"></param>
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<PackageData> 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();
//}
}
/// <summary>
/// 保存图片
/// </summary>
/// <param name="countid"></param>
/// <param name="data"></param>
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<visitorModel>(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<HttpWebRequest> reqList = new List<HttpWebRequest>();
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);
}
}
/// <summary>
/// 记录普通信息
/// </summary>
/// <param name="msg"></param>
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)
{
@ -1221,10 +1299,20 @@ namespace WinFormsAppVisitorDeploy
catch (Exception e)
{
ReqResult = e.Message;
text("SendHttpRequest:" + e.Message);
AppendShowMsg("SendHttpRequest:" + e.Message);
}
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">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="MyLogHelper.cs" />
<Compile Include="MyTaskControlHelper.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">

Loading…
Cancel
Save