/// <summary> /// 更新CaseRunner界面 /// </summary> private void UpdateRunnerView() { if (caseRunnerList.Count > 0) { if (selctRunner != null) { List <MyExecutionDeviceResult> tempExecutionDeviceResults = selctRunner.RunerActuator.NowExecutionResultList; listView_SelectRunner.BeginUpdate(); if (tempExecutionDeviceResults.Count < listView_SelectRunner.Items.Count) { FillExecutionResult(tempExecutionDeviceResults); } else { while (tempExecutionDeviceResults.Count > listView_SelectRunner.Items.Count) { MyExecutionDeviceResult tempRseult = tempExecutionDeviceResults[listView_SelectRunner.Items.Count]; listView_SelectRunner.Items.Add(new ListViewItem(new string[] { listView_SelectRunner.Items.Count.ToString(), tempRseult.caseId.ToString(), tempRseult.startTime, tempRseult.spanTime, tempRseult.result.ToString(), tempRseult.caseTarget + "->" + tempRseult.backContent, tempRseult.additionalRemark })); } } if (listView_SelectRunner.Items.Count - 1 > 0) { listView_SelectRunner.EnsureVisible(listView_SelectRunner.Items.Count - 1); } listView_SelectRunner.EndUpdate(); } foreach (CaseRunner tempRunner in caseRunnerList) { if (tempRunner.RunnerState == CaseActuatorState.Running) { tempRunner.UpdateProgressBar(); } } } }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection();//默认该值为null,不会输出参数数据结果(如果不需要输出可以保持该字段为null) if (yourExecutionContent.MyCaseProtocol == CaseProtocol.vanelife_http) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyVaneHttpExecutionContent nowExecutionContent = yourExecutionContent as MyVaneHttpExecutionContent; myResult.caseProtocol = CaseProtocol.vanelife_http; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; string tempError; string tempUrlAddress; string vanelifeData = CreatVanelifeSendData(nowExecutionContent.caseExecutionContent.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError)); if (nowExecutionContent.myHttpAisleConfig.httpAddress.IsFilled()) { tempUrlAddress = nowExecutionContent.myHttpAisleConfig.httpAddress.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError) + nowExecutionContent.httpTarget; } else { tempUrlAddress = myExecutionDeviceInfo.default_url + nowExecutionContent.httpTarget; } //report Executive Data if (yourExecutiveDelegate != null) { yourExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[vanelife_http]Executive···\r\n{1}\r\n{2}", caseId, tempUrlAddress, vanelifeData)); } //Start Http if (nowExecutionContent.myHttpAisleConfig.httpDataDown.IsFilled()) { httpClient.SendData(tempUrlAddress, vanelifeData, nowExecutionContent.httpMethod, myResult, CaseTool.GetFullPath(nowExecutionContent.myHttpAisleConfig.httpDataDown.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError), MyConfiguration.CaseFilePath)); } else { if (nowExecutionContent.myHttpMultipart.IsFilled()) { //由于vanelife协议要求在Multipart把业务数据全部放在了url中 httpClient.HttpPostData(tempUrlAddress + "?" + vanelifeData, 30000, nowExecutionContent.myHttpMultipart.name, nowExecutionContent.myHttpMultipart.fileName, nowExecutionContent.myHttpMultipart.isFile, nowExecutionContent.myHttpMultipart.fileData, null, myResult); } else { httpClient.SendData(tempUrlAddress, vanelifeData, nowExecutionContent.httpMethod, myResult); } } if (tempError != null) { myResult.additionalError = ("error:" + tempError); } } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; myResult.additionalError = ("error:your CaseProtocol is not Matching RunTimeActuator"); } return(myResult); }
void runerActuator_OnExecutiveResult(string sender, MyExecutionDeviceResult yourResult) { if (tagItem != null) { tagItem.ListView.BeginInvoke(new Action <MyExecutionDeviceResult>(UpdateDateShow), yourResult); } //UpdateDateShow(yourResult); }
/// <summary> /// 更新当前显示信息 /// </summary> /// <param name="yourResult"></param> private void UpdateDateShow(MyExecutionDeviceResult yourResult) { if (tagItem != null && yourResult != null) { tagItem.SubItems[2].Text = yourResult.caseId.ToString(); tagItem.SubItems[3].Text = yourResult.backContent; tagItem.SubItems[4].Text = yourResult.result.ToString(); tagItem.SubItems[5].Text = yourResult.spanTime; } }
/// <summary> /// 获取List<CaseRunner>中的更新信息 /// </summary> /// <param name="runnerList">CaseRunner 列表</param> /// <param name="isUpdataAll">T表示全部更新,F标识局部更新</param> /// <returns>更新信息</returns> private RemoteRunnerInfo GetRunnerInfo(List <CaseRunner> runnerList, bool isUpdataAll) { RemoteRunnerInfo remoteRunnerInfo = new RemoteRunnerInfo(); if (runnerList == null) { return(null); } foreach (CaseRunner tempRunner in runnerList) { if (tempRunner.IsNeedUpdata || isUpdataAll) { tempRunner.IsNeedUpdata = false; RunnerState tempRunnerState = new RunnerState(); if (tempRunner.RunerActuator.NowExecutionResultList != null) { if (tempRunner.RunerActuator.NowExecutionResultList.Count > 0) { MyExecutionDeviceResult tempResult = tempRunner.RunerActuator.NowExecutionResultList[tempRunner.RunerActuator.NowExecutionResultList.Count - 1]; tempRunnerState.RunnerID = runnerList.IndexOf(tempRunner); tempRunnerState.RunnerName = tempRunner.RunnerName; tempRunnerState.NowCell = tempResult.caseId.ToString(); tempRunnerState.CellResult = tempResult.result.ToString(); tempRunnerState.State = tempRunner.RunnerState.ToString(); tempRunnerState.Time = tempResult.spanTime; tempRunnerState.RunDetails = tempResult.backContent; tempRunnerState.RunnerProgress = tempRunner.RunerActuator.RunProgress; remoteRunnerInfo.AddRunnerState(tempRunnerState); } else if (isUpdataAll)//对于空NowExecutionResultList来说,如果要求全部更新则要求构造一个初始的数据体 { tempRunnerState.RunnerID = runnerList.IndexOf(tempRunner); tempRunnerState.RunnerName = tempRunner.RunnerName; tempRunnerState.NowCell = ""; tempRunnerState.CellResult = ""; tempRunnerState.State = tempRunner.RunnerState.ToString(); tempRunnerState.Time = ""; tempRunnerState.RunDetails = ""; tempRunnerState.RunnerProgress = tempRunner.RunerActuator.RunProgress; remoteRunnerInfo.AddRunnerState(tempRunnerState); } else { tempRunnerState.RunnerID = runnerList.IndexOf(tempRunner); tempRunnerState.RunnerName = tempRunner.RunnerName; tempRunnerState.State = tempRunner.RunnerState.ToString(); tempRunnerState.RunnerProgress = tempRunner.RunerActuator.RunProgress; remoteRunnerInfo.AddRunnerState(tempRunnerState); } } } } return(remoteRunnerInfo); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); if (yourExecutionContent.MyCaseProtocol == CaseProtocol.http) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyBasicHttpExecutionContent nowExecutionContent = yourExecutionContent as MyBasicHttpExecutionContent; myResult.caseProtocol = CaseProtocol.http; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; string tempError; string httpUri; string httpBody = null; List <KeyValuePair <string, string> > httpHeads = null; httpUri = nowExecutionContent.httpUri.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (httpUri.StartsWith("@")) { httpUri = myExecutionDeviceInfo.default_url + httpUri.Remove(0, 1); } if (nowExecutionContent.httpBody.IsFilled()) { httpBody = nowExecutionContent.httpBody.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); } if (nowExecutionContent.httpHeads.Count > 0) { httpHeads = new List <KeyValuePair <string, string> >(); foreach (var tempHead in nowExecutionContent.httpHeads) { httpHeads.Add(new KeyValuePair <string, string>(tempHead.Key, tempHead.Value.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError))); } } //report Executive Data if (yourExecutiveDelegate != null) { if (httpBody != null) { yourExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[http]Executive···\r\n{1}\r\n{2}", caseId, httpUri, httpBody)); } else { yourExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[http]Executive···\r\n{1}", caseId, httpUri)); } } //Start Http if (nowExecutionContent.myMultipartList.Count > 0) { List <MyCommonHelper.NetHelper.MyWebTool.HttpMultipartDate> myMultiparts = new List <MyCommonHelper.NetHelper.MyWebTool.HttpMultipartDate>(); foreach (HttpMultipart tempPt in nowExecutionContent.myMultipartList) { if (tempPt.IsFilled()) { myMultiparts.Add(new MyCommonHelper.NetHelper.MyWebTool.HttpMultipartDate(tempPt.name, tempPt.fileName, null, tempPt.isFile, tempPt.fileData)); } } httpClient.HttpPostData(httpUri, httpHeads, httpBody, myMultiparts, null, MyConfiguration.PostFileTimeOut, null, myResult); } else if (nowExecutionContent.myHttpAisleConfig.httpDataDown.IsFilled()) { httpClient.SendData(httpUri, httpBody, nowExecutionContent.httpMethod, httpHeads, myResult, CaseTool.GetFullPath(nowExecutionContent.myHttpAisleConfig.httpDataDown.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError), MyConfiguration.CaseFilePath)); } else { httpClient.SendData(httpUri, httpBody, nowExecutionContent.httpMethod, httpHeads, myResult); } if (tempError != null) { myResult.additionalError = ("error:" + tempError); } } else { myResult.additionalError = ("error:your CaseProtocol is not Matching RunTimeActuator"); myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; } return(myResult); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActuator.CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { List <string> errorList = new List <string>(); string tempError = null; MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); Action <string, CaseActuatorOutPutType, string> ExecutiveDelegate = (innerSender, outType, yourContent) => { if (yourExecutiveDelegate != null) { yourExecutiveDelegate(innerSender, outType, yourContent); } }; Func <string, bool> DealNowError = (errerData) => { if (errerData != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, errerData); errorList.Add(errerData); return(true); } return(false); }; Func <string, string, string, bool> DealNowResultError = (errerData, actionType, keyName) => { if (DealNowError(errerData)) { ExecutiveDelegate(string.Format("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][{0}]", actionType), CaseActuatorOutPutType.ExecutiveError, string.Format("static data {0} error with the key :{1} ", actionType, keyName)); return(true); } else { return(false); } }; if (yourExecutionContent.MyCaseProtocol == CaseProtocol.console) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyConsoleExecutionContent nowExecutionContent = yourExecutionContent as MyConsoleExecutionContent; myResult.caseProtocol = CaseProtocol.console; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; myResult.startTime = DateTime.Now.ToString("HH:mm:ss"); System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch(); myWatch.Start(); #region Show myResult.backContent = nowExecutionContent.showContent.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); DealNowError(tempError); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】Executive···\r\n【Console】\r\n{1}", caseId, myResult.backContent)); #endregion #region Add if (nowExecutionContent.staticDataAddList.Count > 0) { foreach (var addInfo in nowExecutionContent.staticDataAddList) { switch (CaseRunTimeDataTypeEngine.dictionaryStaticDataTypeClass[addInfo.StaticDataType]) { //caseStaticDataKey case CaseStaticDataClass.caseStaticDataKey: string tempRunTimeDataKey; if (addInfo.StaticDataType == CaseStaticDataType.caseStaticData_vaule) { tempRunTimeDataKey = addInfo.ConfigureData.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); } else { ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Add]", CaseActuatorOutPutType.ExecutiveError, string.Format("find nonsupport Protocol")); break; } //如果使用提供的方式进行添加是不会出现错误的(遇到重复会覆盖,只有发现多个同名Key才会返回错误), 不过getTargetContentData需要处理用户数据可能出现错误。 if (!DealNowResultError(tempError, "Add", addInfo.Name)) { yourActuatorStaticDataCollection.AddStaticDataKey(addInfo.Name, tempRunTimeDataKey); ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Add]", CaseActuatorOutPutType.ExecutiveInfo, string.Format("static data add success with the key :{0} ", addInfo.Name)); } break; //caseStaticDataParameter case CaseStaticDataClass.caseStaticDataParameter: IRunTimeStaticData tempRunTimeStaticData; string tempTypeError; if (CaseRunTimeDataTypeEngine.dictionaryStaticDataParameterAction[addInfo.StaticDataType](out tempRunTimeStaticData, out tempTypeError, addInfo.ConfigureData.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError))) { if (!DealNowResultError(tempError, "Add", addInfo.Name)) { yourActuatorStaticDataCollection.AddStaticDataParameter(addInfo.Name, tempRunTimeStaticData); ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Add]", CaseActuatorOutPutType.ExecutiveInfo, string.Format("static data add success with the key :{0} ", addInfo.Name)); } } else { DealNowResultError("[yourActuatorStaticDataCollection][caseStaticDataParameter][GetStaticDataAction] error", "Add", addInfo.Name); } break; //caseStaticDataSource case CaseStaticDataClass.caseStaticDataSource: IRunTimeDataSource tempRunTimeDataSource; if (CaseRunTimeDataTypeEngine.dictionaryStaticDataSourceAction[addInfo.StaticDataType](out tempRunTimeDataSource, out tempTypeError, addInfo.ConfigureData.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError))) { if (!DealNowResultError(tempError, "Add", addInfo.Name)) { yourActuatorStaticDataCollection.AddStaticDataSouce(addInfo.Name, tempRunTimeDataSource); ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Add]", CaseActuatorOutPutType.ExecutiveInfo, string.Format("static data add success with the key :{0} ", addInfo.Name)); } } else { DealNowResultError("[yourActuatorStaticDataCollection][caseStaticDataSource][GetStaticDataAction] error", "Add", addInfo.Name); } break; default: DealNowError("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Add] find nonsupport Protocol"); break; } } } #endregion #region Set if (nowExecutionContent.staticDataSetList.Count > 0) { foreach (var addInfo in nowExecutionContent.staticDataSetList) { string tempSetVauleStr = addInfo.Value.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (!DealNowResultError(tempError, "Set", addInfo.Key)) { if (yourActuatorStaticDataCollection.SetStaticDataValue(addInfo.Key, tempSetVauleStr)) { ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Set]", CaseActuatorOutPutType.ExecutiveInfo, string.Format("static data set success with the key :{0} ", addInfo.Key)); } else { DealNowResultError("[yourActuatorStaticDataCollection.SetStaticData] error", "Set", addInfo.Key); } } } } #endregion #region Del if (nowExecutionContent.staticDataDelList.Count > 0) { foreach (var delInfo in nowExecutionContent.staticDataDelList) { string tempDelVauleStr = delInfo.Value.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (!DealNowResultError(tempError, "Del", delInfo.Value.GetTargetContentData())) { if (yourActuatorStaticDataCollection.RemoveStaticData(tempDelVauleStr, delInfo.Key)) { ExecutiveDelegate("[CaseProtocolExecutionForConsole][ExecutionDeviceRun][Del]", CaseActuatorOutPutType.ExecutiveInfo, string.Format("static data del success with the key :{0} ", tempDelVauleStr)); } else { DealNowResultError("[yourActuatorStaticDataCollection.RemoveStaticData] error", "Del", delInfo.Value.GetTargetContentData()); } } } } #endregion myWatch.Stop(); myResult.spanTime = myResult.requestTime = myWatch.ElapsedMilliseconds.ToString(); } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; DealNowError(myResult.backContent); } if (errorList.Count > 0) { myResult.additionalError = errorList.MyToString("\r\n"); } return(myResult); }
/// <summary> /// i will Send Data /// </summary> /// <param name="url"> url </param> /// <param name="data"> param </param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <param name="saveFileName">the file will save with this name</param> /// <returns>back</returns> public void SendData(string url, string data, string method, MyExecutionDeviceResult myEdr, string saveFileName) { SendData(url, data, method, null, myEdr, saveFileName); }
/// <summary> /// i will Send Data /// </summary> /// <param name="url"> url </param> /// <param name="data"> param if method is not POST it will add to the url</param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <returns>back </returns> public void SendData(string url, string data, string method, List <KeyValuePair <string, string> > heads, MyExecutionDeviceResult myEdr) { MyWebTool.MyHttpResponse httpResponse = myHttp.SendHttpRequest(url, data, method, heads, myHttp.IsWithDefaultCookieContainer, null, null); myEdr.backContent = isShowRawResponse ? httpResponse.ResponseRaw : httpResponse.ResponseBody; MyWebTool.HttpTimeLine timeline = httpResponse.TimeLine ?? new MyWebTool.HttpTimeLine(); myEdr.startTime = timeline.StartTime.ToString("HH:mm:ss"); myEdr.requestTime = myEdr.spanTime = timeline.ElapsedTime.ToString(); }
public void HttpPostData(string url, List <KeyValuePair <string, string> > heads, string bodyData, List <MyWebTool.HttpMultipartDate> multipartDateList, string bodyMultipartParameter, int timeOut, Encoding yourBodyEncoding, MyExecutionDeviceResult myEdr) { MyWebTool.MyHttpResponse httpResponse = myHttp.SendMultipartRequest(url, heads, myHttp.IsWithDefaultCookieContainer, bodyData, multipartDateList, bodyMultipartParameter, yourBodyEncoding, null, null); myEdr.backContent = isShowRawResponse ? httpResponse.ResponseRaw : httpResponse.ResponseBody; MyWebTool.HttpTimeLine timeline = httpResponse.TimeLine ?? new MyWebTool.HttpTimeLine(); myEdr.startTime = timeline.StartTime.ToString("HH:mm:ss"); myEdr.requestTime = myEdr.spanTime = timeline.ElapsedTime.ToString(); }
/// <summary> /// i will Send Data with multipart,if you do not want updata any file you can set isFile is false and set filePath is null /// </summary> /// <param name="url">url</param> /// <param name="timeOut">timeOut</param> /// <param name="name">Parameter name</param> /// <param name="filename">filename</param> /// <param name="isFile">is a file</param> /// <param name="filePath">file path or cmd</param> /// <param name="bodyParameter">the other Parameter in body</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <returns>back</returns> public void HttpPostData(string url, int timeOut, string name, string filename, bool isFile, string filePath, string bodyParameter, MyExecutionDeviceResult myEdr) { MyWebTool.MyHttpResponse httpResponse = myHttp.SendMultipartRequest(url, null, myHttp.IsWithDefaultCookieContainer, null, new List <MyWebTool.HttpMultipartDate>() { new MyWebTool.HttpMultipartDate(name, filename, null, isFile, filePath) }, bodyParameter, null, null, null); myEdr.backContent = isShowRawResponse ? httpResponse.ResponseRaw : httpResponse.ResponseBody; MyWebTool.HttpTimeLine timeline = httpResponse.TimeLine ?? new MyWebTool.HttpTimeLine(); myEdr.startTime = timeline.StartTime.ToString("HH:mm:ss"); myEdr.requestTime = myEdr.spanTime = timeline.ElapsedTime.ToString(); }
/// <summary> /// i will Send Data /// </summary> /// <param name="url"> url </param> /// <param name="data"> param if method is not POST it will add to the url</param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <returns>back </returns> public static string SendData(string url, string data, string method, MyExecutionDeviceResult myEdr) { return(SendData(url, data, method, null, myEdr)); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { List <string> errorList = new List <string>(); string tempError = null; MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); Action <string, CaseActuatorOutPutType, string> ExecutiveDelegate = (innerSender, outType, yourContent) => { if (yourExecutiveDelegate != null) { yourExecutiveDelegate(innerSender, outType, yourContent); } }; Action <string> DealExecutiveError = (errerData) => { if (errerData != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, errerData); errorList.Add(errerData); } }; if (yourExecutionContent.MyCaseProtocol == CaseProtocol.activeMQ) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyActiveMQExecutionContent nowExecutionContent = yourExecutionContent as MyActiveMQExecutionContent; myResult.caseProtocol = CaseProtocol.activeMQ; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; myResult.startTime = DateTime.Now.ToString("HH:mm:ss"); StringBuilder tempCaseOutContent = new StringBuilder(); System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch(); myWatch.Start(); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[activeMQ]Executive···", caseId)); #region Subscribe foreach (var tempConsumer in nowExecutionContent.consumerSubscribeList) { if (tempConsumer.ConsumerType == "queue" || tempConsumer.ConsumerType == "topic") { if (activeMQ.SubscribeConsumer(tempConsumer.ConsumerName, tempConsumer.ConsumerType == "queue", tempConsumer.ConsumerTopicDurable)) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("{0}://{1} subscribe success", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } else { DealExecutiveError(string.Format("{0}://{1} subscribe fail", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } } else { DealExecutiveError(string.Format("{0}://{1} subscribe fail [not support this consumer type]", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } } #endregion #region UnSubscribe foreach (var tempConsumer in nowExecutionContent.unConsumerSubscribeList) { if (tempConsumer.ConsumerType == "queue" || tempConsumer.ConsumerType == "topic") { if (activeMQ.UnSubscribeConsumer(string.Format("{0}://{1}", tempConsumer.ConsumerType, tempConsumer.ConsumerName)) > 0) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("{0}://{1} unsubscribe success", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } else { DealExecutiveError(string.Format("{0}://{1} unsubscribe fail", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } } else { DealExecutiveError(string.Format("{0}://{1} unsubscribe fail [not support this consumer type]", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } } #endregion #region Send foreach (var tempOneSender in nowExecutionContent.producerDataSendList) { if (tempOneSender.Key.ProducerType == "queue" || tempOneSender.Key.ProducerType == "topic") { string tempMessageSend = tempOneSender.Value.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (tempError != null) { DealExecutiveError(string.Format("this case get static data errer with [{0}]", tempOneSender.Value.GetTargetContentData())); tempCaseOutContent.AppendLine(string.Format("{0}://{1} send message fail [get static data errer]", tempOneSender.Key.ProducerType, tempOneSender.Key.ProducerName)); } else { MessageType tempMessageType; if (Enum.TryParse <MessageType>(tempOneSender.Key.MessageType, out tempMessageType)) { if (activeMQ.PublishMessage(tempOneSender.Key.ProducerName, tempMessageSend, tempOneSender.Key.ProducerType == "topic", tempMessageType)) { string tempReportStr = string.Format("{0}://{1} send message success", tempOneSender.Key.ProducerType, tempOneSender.Key.ProducerName); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, tempReportStr); tempCaseOutContent.AppendLine(tempReportStr); } else { string tempReportStr = string.Format("{0}://{1} send message fail [{2}]", tempOneSender.Key.ProducerType, tempOneSender.Key.ProducerName, activeMQ.NowErrorMes); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, tempReportStr); tempCaseOutContent.AppendLine(tempReportStr); } } else { DealExecutiveError(string.Format("get MessageType errer with [{0}]", tempOneSender.Key.MessageType)); tempCaseOutContent.AppendLine(string.Format("{0}://{1} send message fail [get MessageType errer]", tempOneSender.Key.ProducerType, tempOneSender.Key.ProducerName)); } } } else { tempCaseOutContent.Append(string.Format("{0}://{1} send message fail [not support this producer type]", tempOneSender.Key.ProducerType, tempOneSender.Key.ProducerName)); } } #endregion #region Receive if (nowExecutionContent.consumerMessageReceiveList.Count > 0) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, "Receive your activeMQ messages"); } foreach (var tempConsumer in nowExecutionContent.consumerMessageReceiveList) { if (tempConsumer.ConsumerName != null) { if (tempConsumer.ConsumerType == "queue" || tempConsumer.ConsumerType == "topic") { List <KeyValuePair <string, string> > oneMessageReceive = activeMQ.ReadConsumerMessage(string.Format("{0}://{1}", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); foreach (KeyValuePair <string, string> tempMessage in oneMessageReceive) { string tempNowReceviceData = string.Format("{0} Receive {1}", tempMessage.Key, tempMessage.Value); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, tempNowReceviceData); tempCaseOutContent.AppendLine(tempNowReceviceData); } } else { DealExecutiveError(string.Format("{0}://{1} receive fail [not support this consumer type]", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); tempCaseOutContent.AppendLine(string.Format("{0}://{1} receive fail ", tempConsumer.ConsumerType, tempConsumer.ConsumerName)); } } else { List <KeyValuePair <string, string> > oneMessageReceive = activeMQ.ReadConsumerMessage(); foreach (KeyValuePair <string, string> tempMessage in oneMessageReceive) { string tempNowReceviceData = string.Format("{0} Receive {1}", tempMessage.Key, tempMessage.Value); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, tempNowReceviceData); tempCaseOutContent.AppendLine(tempNowReceviceData); } } } #endregion myWatch.Stop(); myResult.spanTime = myResult.requestTime = myWatch.ElapsedMilliseconds.ToString(); myResult.backContent = tempCaseOutContent.ToString(); } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; DealExecutiveError(myResult.backContent); } if (errorList.Count > 0) { myResult.additionalError = errorList.MyToString("\r\n"); } return(myResult); }
/// <summary> /// i will Send Data (逐字节保存) /// </summary> /// <param name="url"> url </param> /// <param name="data"> param </param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <param name="saveFileName">the file will save with this name</param> /// <returns>back</returns> public static string SendDataSaveEx(string url, string data, string method, MyExecutionDeviceResult myEdr, string saveFileName) { return(SendDataSaveEx(url, data, method, null, myEdr, saveFileName)); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { List <string> errorList = new List <string>(); string tempError = null; MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); //向UI推送执行过程信息 Action <string, CaseActuatorOutPutType, string> ExecutiveDelegate = (innerSender, outType, yourContent) => { if (yourExecutiveDelegate != null) { yourExecutiveDelegate(innerSender, outType, yourContent); } }; //处理执行错误(执行器无法执行的错误) Action <string> DealExecutiveError = (errerData) => { if (errerData != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, errerData); errorList.Add(errerData); } }; if (yourExecutionContent.MyCaseProtocol == CaseProtocol.ssh) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MySshExecutionContent nowExecutionContent = yourExecutionContent as MySshExecutionContent; myResult.caseProtocol = CaseProtocol.ssh; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; myResult.startTime = DateTime.Now.ToString("HH:mm:ss"); StringBuilder tempCaseOutContent = new StringBuilder(); System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch(); myWatch.Start(); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[ssh]Executive···", caseId)); string nowSshCmd = nowExecutionContent.sshContent.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (tempError != null) { DealExecutiveError(string.Format("this case get static data errer with [{0}]", nowExecutionContent.sshContent.GetTargetContentData())); tempCaseOutContent.AppendLine("error with static data"); } else { try { sshShell.WriteLine(nowSshCmd); string tempResult = sshShell.Expect(); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, tempResult); tempCaseOutContent.AppendLine(tempResult); } catch (Exception ex) { DealExecutiveError(ex.Message); tempCaseOutContent.AppendLine(ex.Message); } } myWatch.Stop(); myResult.spanTime = myResult.requestTime = myWatch.ElapsedMilliseconds.ToString(); myResult.backContent = tempCaseOutContent.ToString(); } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; DealExecutiveError(myResult.backContent); } if (errorList.Count > 0) { myResult.additionalError = errorList.MyToString("\r\n"); } return(myResult); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { List <string> errorList = new List <string>(); string tempError = null; MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); //向UI推送执行过程信息 Action <string, CaseActuatorOutPutType, string> ExecutiveDelegate = (innerSender, outType, yourContent) => { if (yourExecutiveDelegate != null) { yourExecutiveDelegate(innerSender, outType, yourContent); } }; //处理执行错误(执行器无法执行的错误) Action <string> DealExecutiveError = (errerData) => { if (errerData != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, errerData); errorList.Add(errerData); } }; if (yourExecutionContent.MyCaseProtocol == CaseProtocol.com) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyComExecutionContent nowExecutionContent = yourExecutionContent as MyComExecutionContent; myResult.caseProtocol = CaseProtocol.com; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; myResult.startTime = DateTime.Now.ToString("HH:mm:ss"); StringBuilder tempCaseOutContent = new StringBuilder(); System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch(); myWatch.Start(); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[com]Executive···", caseId)); #region Send if (nowExecutionContent.isSend) { string nowComData = nowExecutionContent.comContentToSend.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (tempError != null) { DealExecutiveError(string.Format("this case get static data errer with [{0}]", nowExecutionContent.comContentToSend.GetTargetContentData())); tempCaseOutContent.AppendLine("error with static data"); } else { byte[] nowSendBytes; if (nowExecutionContent.comSendEncoding == null) { try { nowSendBytes = MyBytes.HexStringToByte(nowComData, HexaDecimal.hex16, ShowHexMode.space); } catch { nowSendBytes = null; } } else { try { nowSendBytes = nowExecutionContent.comSendEncoding.GetBytes(nowComData); } catch { nowSendBytes = null; } } if (nowSendBytes == null) { DealExecutiveError(string.Format("can not change data to bytes with [{0}]", nowExecutionContent.comContentToSend.GetTargetContentData())); tempCaseOutContent.AppendLine("error with com data"); } else { if (mySerialPort.Send(nowSendBytes)) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, "send sucess"); tempCaseOutContent.AppendLine("send sucess"); } else { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, mySerialPort.ErroerMessage); tempCaseOutContent.AppendLine(mySerialPort.ErroerMessage); } } } } #endregion #region receive if (nowExecutionContent.isReceive) { if (nowExecutionContent.comSleepTime > 0) { System.Threading.Thread.Sleep(nowExecutionContent.comSleepTime); } byte[] recweiveBytes = mySerialPort.ReadAllBytes(); if (recweiveBytes != null) { string receiveStr; if (nowExecutionContent.comReceiveEncoding == null) { receiveStr = MyBytes.ByteToHexString(recweiveBytes, HexaDecimal.hex16, ShowHexMode.space); } else { try { receiveStr = nowExecutionContent.comReceiveEncoding.GetString(recweiveBytes); } catch { receiveStr = null; } } if (receiveStr != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, receiveStr); tempCaseOutContent.AppendLine(receiveStr); } else { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, string.Format("can not Encoding your data with {0}", MyBytes.ByteToHexString(recweiveBytes, HexaDecimal.hex16, ShowHexMode.space))); tempCaseOutContent.AppendLine("[error]receive data error can not encoding receive data"); } } } #endregion myWatch.Stop(); myResult.spanTime = myResult.requestTime = myWatch.ElapsedMilliseconds.ToString(); myResult.backContent = tempCaseOutContent.ToString(); } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; DealExecutiveError(myResult.backContent); } if (errorList.Count > 0) { myResult.additionalError = errorList.MyToString("\r\n"); } return(myResult); }
public MyExecutionDeviceResult ExecutionDeviceRun(ICaseExecutionContent yourExecutionContent, CaseActionActuator.delegateGetExecutiveData yourExecutiveDelegate, string sender, ActuatorStaticDataCollection yourActuatorStaticDataCollection, int caseId) { List <string> errorList = new List <string>(); string tempError = null; MyExecutionDeviceResult myResult = new MyExecutionDeviceResult(); myResult.staticDataResultCollection = new System.Collections.Specialized.NameValueCollection(); //向UI推送执行过程信息 Action <string, CaseActuatorOutPutType, string> ExecutiveDelegate = (innerSender, outType, yourContent) => { if (yourExecutiveDelegate != null) { yourExecutiveDelegate(innerSender, outType, yourContent); } }; //处理执行错误(执行器无法执行的错误) Action <string> DealExecutiveError = (errerData) => { if (errerData != null) { ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveError, errerData); errorList.Add(errerData); } }; if (yourExecutionContent.MyCaseProtocol == CaseProtocol.mysql) { //在调用该函数前保证nowExecutionContent.ErrorMessage为空,且as一定成功 MyMySqlExecutionContent nowExecutionContent = yourExecutionContent as MyMySqlExecutionContent; myResult.caseProtocol = CaseProtocol.mysql; myResult.caseTarget = nowExecutionContent.MyExecutionTarget; myResult.startTime = DateTime.Now.ToString("HH:mm:ss"); StringBuilder tempCaseOutContent = new StringBuilder(); System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch(); myWatch.Start(); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, string.Format("【ID:{0}】[mysql]Executive···", caseId)); string nowSqlCmd = nowExecutionContent.sqlContent.GetTargetContentData(yourActuatorStaticDataCollection, myResult.staticDataResultCollection, out tempError); if (tempError != null) { DealExecutiveError(string.Format("this case get static data errer with [{0}]", nowExecutionContent.sqlContent.GetTargetContentData())); tempCaseOutContent.AppendLine("error with static data"); } else { if (nowExecutionContent.isPosition) { string sqlResult = mySqlDrive.ExecuteQuery(nowSqlCmd, nowExecutionContent.rowIndex, nowExecutionContent.columnIndex); if (sqlResult == null) { tempCaseOutContent.AppendLine(string.Format("error in [ExecuteQuery] :{0}", mySqlDrive.NowError)); DealExecutiveError(mySqlDrive.NowError); } else { tempCaseOutContent.AppendLine(sqlResult); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, sqlResult); } } else { System.Data.DataTable sqlResult = mySqlDrive.ExecuteQuery(nowSqlCmd); if (sqlResult == null) { tempCaseOutContent.AppendLine(string.Format("error in [ExecuteQuery] :{0}", mySqlDrive.NowError)); DealExecutiveError(mySqlDrive.NowError); } else { string json = Newtonsoft.Json.JsonConvert.SerializeObject(sqlResult, Newtonsoft.Json.Formatting.Indented); ExecutiveDelegate(sender, CaseActuatorOutPutType.ExecutiveInfo, json); tempCaseOutContent.AppendLine(json); } } } myWatch.Stop(); myResult.spanTime = myResult.requestTime = myWatch.ElapsedMilliseconds.ToString(); myResult.backContent = tempCaseOutContent.ToString(); } else { myResult.backContent = "error:your CaseProtocol is not Matching RunTimeActuator"; DealExecutiveError(myResult.backContent); } if (errorList.Count > 0) { myResult.additionalError = errorList.MyToString("\r\n"); } return(myResult); }
/// <summary> /// i will Send Data /// </summary> /// <param name="url"> url </param> /// <param name="data"> param if method is not POST it will add to the url</param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <returns>back </returns> public static string SendData(string url, string data, string method, List <KeyValuePair <string, string> > heads, MyExecutionDeviceResult myEdr) { string re = ""; bool hasBody = !string.IsNullOrEmpty(data); bool needBody = method.ToUpper() == "POST" || method.ToUpper() == "PUT"; Stopwatch myWatch = new Stopwatch(); try { //except POST other data will add the url,if you want adjust the ruleschange here if (!needBody && hasBody) { url += "?" + data; } WebRequest wr = WebRequest.Create(url); wr.Timeout = httpTimeOut; //HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url); wr.Method = method; if (heads == null) { wr.ContentType = "application/x-www-form-urlencoded"; } MyWebTool.HttpHelper.AddHttpHeads((HttpWebRequest)wr, heads); //((HttpWebRequest)wr).KeepAlive = true; //wr.Headers.Remove(HttpRequestHeader.Connection); //wr.Headers.Add(HttpRequestHeader.Connection, "close"); //wr.Headers.Add(HttpRequestHeader.KeepAlive, "false"); char[] reserved = { '?', '=', '&' }; StringBuilder UrlEncoded = new StringBuilder(); byte[] SomeBytes = null; myEdr.startTime = DateTime.Now.ToString("HH:mm:ss"); myWatch.Start(); if (needBody) { if (hasBody) { SomeBytes = Encoding.UTF8.GetBytes(data); wr.ContentLength = SomeBytes.Length; myWatch.Reset(); myWatch.Start(); Stream newStream = wr.GetRequestStream(); newStream.Write(SomeBytes, 0, SomeBytes.Length); myEdr.requestTime = myWatch.ElapsedMilliseconds.ToString(); //myWatch.Stop(); newStream.Close(); } else { wr.ContentLength = 0; } } WebResponse result = wr.GetResponse(); myWatch.Stop(); Stream receiveStream = result.GetResponseStream(); using (var httpStreamReader = new StreamReader(receiveStream, Encoding.UTF8)) { re += httpStreamReader.ReadToEnd(); } } catch (WebException wex) { if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { re = "StatusCode: " + Convert.ToInt32(((HttpWebResponse)wex.Response).StatusCode) + "\r\n"; using (var reader = new StreamReader(errorResponse.GetResponseStream())) { re += reader.ReadToEnd(); } } } else { re = wex.Message; } } catch (Exception ex) { re = "Unknow Error: " + ex.Message; ErrorLog.PutInLog("ID:0957 " + ex.Message); } if (myWatch.IsRunning) { myWatch.Stop(); } myEdr.spanTime = myWatch.ElapsedMilliseconds.ToString(); myEdr.backContent = re; return(re); }
public static string HttpPostData(string url, List <KeyValuePair <string, string> > heads, string bodyData, List <MyWebTool.HttpMultipartDate> multipartDateList, string bodyMultipartParameter, int timeOut, Encoding yourBodyEncoding, MyExecutionDeviceResult myEdr) { string responseContent = null; Encoding httpBodyEncoding = Encoding.UTF8; string defaultMultipartContentType = "application/octet-stream"; NameValueCollection stringDict = new NameValueCollection(); if (yourBodyEncoding != null) { httpBodyEncoding = yourBodyEncoding; } //解析快捷Multipart表单形式post参数 if (bodyMultipartParameter != null) { string[] sArray = bodyMultipartParameter.Split('&'); foreach (string tempStr in sArray) { int myBreak = tempStr.IndexOf('='); if (myBreak == -1) { myEdr.backContent = "can't find '=' in [bodyMultipartParameter]"; return("can't find ="); } stringDict.Add(tempStr.Substring(0, myBreak), tempStr.Substring(myBreak + 1)); } } var memStream = new MemoryStream(); var webRequest = (HttpWebRequest)WebRequest.Create(url); //写入http头 MyWebTool.HttpHelper.AddHttpHeads(webRequest, heads); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); // 边界符 var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = timeOut; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; //写如常规body if (bodyData != null) { var bodybytes = httpBodyEncoding.GetBytes(bodyData); memStream.Write(bodybytes, 0, bodybytes.Length); } if (multipartDateList != null) { foreach (MyWebTool.HttpMultipartDate nowMultipart in multipartDateList) { //Console.WriteLine(System.DateTime.Now.Ticks); //const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: {2}\r\n\r\n"; string nowPartHeader = "Content-Disposition: form-data"; if (nowMultipart.Name != null) { nowPartHeader += string.Format("; name=\"{0}\"", nowMultipart.Name); } if (nowMultipart.FileName != null) { nowPartHeader += string.Format("; filename=\"{0}\"", nowMultipart.FileName); } nowPartHeader += "\r\n"; nowPartHeader += string.Format("Content-Type: {0}", nowMultipart.ContentType == null ? defaultMultipartContentType : nowMultipart.ContentType); nowPartHeader += "\r\n\r\n"; //Console.WriteLine(System.DateTime.Now.Ticks); byte[] nowHeaderbytes = httpBodyEncoding.GetBytes(nowPartHeader); memStream.Write(Encoding.ASCII.GetBytes("\r\n"), 0, Encoding.ASCII.GetBytes("\r\n").Length); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(nowHeaderbytes, 0, nowHeaderbytes.Length); //MultipartDate if (nowMultipart.IsFile) { try { using (var fileStream = new FileStream(nowMultipart.FileData, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024]; int bytesRead; // =0 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } } } catch (Exception ex) { responseContent = "Error: " + ex.Message + "\r\n"; ErrorLog.PutInLog("ID:0544 " + ex.InnerException); myEdr.backContent = responseContent; return(responseContent); } } else { byte[] myCmd = httpBodyEncoding.GetBytes(nowMultipart.FileData == null ? "" : nowMultipart.FileData); memStream.Write(myCmd, 0, myCmd.Length); } } } //快捷写入写入POST非文件参数 if (bodyMultipartParameter != null) { //写入字符串的Key string bodyParameterFormat = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}"; for (int i = 0; i < stringDict.Count; i++) { try { byte[] formitembytes = httpBodyEncoding.GetBytes(string.Format(bodyParameterFormat, stringDict.GetKey(i), stringDict.Get(i))); memStream.Write(formitembytes, 0, formitembytes.Length); } catch (Exception ex) { responseContent = "can not send :" + ex.Message; myEdr.backContent = responseContent; return(responseContent); } } } //写入最后的结束边界符 if (!(bodyMultipartParameter == null && multipartDateList == null)) { memStream.Write(Encoding.ASCII.GetBytes("\r\n"), 0, Encoding.ASCII.GetBytes("\r\n").Length); memStream.Write(endBoundary, 0, endBoundary.Length); } webRequest.ContentLength = memStream.Length; Stopwatch myWatch = new Stopwatch(); myEdr.startTime = DateTime.Now.ToString("HH:mm:ss"); myWatch.Start(); //开始请求 try { var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { if (showResponseHeads) { responseContent = httpWebResponse.Headers.ToString(); } responseContent += httpStreamReader.ReadToEnd(); } myWatch.Stop(); httpWebResponse.Close(); webRequest.Abort(); } catch (WebException wex) { responseContent = string.Format("Error:{0}\r\n", wex.Message); if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { responseContent += "StatusCode: " + Convert.ToInt32(((HttpWebResponse)wex.Response).StatusCode) + "\r\n"; using (var reader = new StreamReader(errorResponse.GetResponseStream())) { responseContent += reader.ReadToEnd(); } } } else { responseContent += "WebException->Response is null"; } } catch (Exception ex) { responseContent = ex.Message; ErrorLog.PutInLog("ID:0090 " + ex.InnerException); } if (myWatch.IsRunning) { myWatch.Stop(); } myEdr.spanTime = myWatch.ElapsedMilliseconds.ToString(); myEdr.backContent = responseContent; return(responseContent); }
/// <summary> /// i will Send Data (逐字节保存) /// </summary> /// <param name="url"> url </param> /// <param name="data"> param </param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <param name="saveFileName">the file will save with this name</param> /// <returns>back</returns> public static string SendDataSaveEx(string url, string data, string method, List <KeyValuePair <string, string> > heads, MyExecutionDeviceResult myEdr, string saveFileName) { string re = ""; bool hasBody = !string.IsNullOrEmpty(data); bool needBody = method.ToUpper() == "POST" || method.ToUpper() == "PUT"; Stopwatch myWatch = new Stopwatch(); try { //except POST other data will add the url,if you want adjust the ruleschange here if (!needBody && hasBody) { url += "?" + data; } WebRequest wr = WebRequest.Create(url); wr.Timeout = httpTimeOut; //HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url); wr.Method = method; if (heads == null) { wr.ContentType = "application/x-www-form-urlencoded"; } MyWebTool.HttpHelper.AddHttpHeads((HttpWebRequest)wr, heads); //((HttpWebRequest)wr).KeepAlive = true; //wr.Headers.Remove(HttpRequestHeader.Connection); //wr.Headers.Add(HttpRequestHeader.Connection, "close"); //wr.Headers.Add(HttpRequestHeader.KeepAlive, "false"); char[] reserved = { '?', '=', '&' }; StringBuilder UrlEncoded = new StringBuilder(); byte[] SomeBytes = null; myEdr.startTime = DateTime.Now.ToString("HH:mm:ss"); myWatch.Start(); if (needBody) { if (hasBody) { SomeBytes = Encoding.UTF8.GetBytes(data); wr.ContentLength = SomeBytes.Length; myWatch.Reset(); myWatch.Start(); Stream newStream = wr.GetRequestStream(); newStream.Write(SomeBytes, 0, SomeBytes.Length); myEdr.requestTime = myWatch.ElapsedMilliseconds.ToString(); //myWatch.Stop(); newStream.Close(); } else { wr.ContentLength = 0; } } WebResponse result = wr.GetResponse(); myWatch.Stop(); Stream ReceiveStream = result.GetResponseStream(); /* * Byte[] read = new Byte[512]; * int bytes = ReceiveStream.Read(read, 0, 512); * * re = ""; * while (bytes > 0) * { * Encoding encode = System.Text.Encoding.GetEncoding("UTF-8"); * re += encode.GetString(read, 0, bytes); * bytes = ReceiveStream.Read(read, 0, 512); * } */ byte[] infbytes = new byte[10240]; int tempLen = 512; int offset = 0; //数据最多20k可以不需要分段读取 while (tempLen - 512 >= 0) { tempLen = ReceiveStream.Read(infbytes, offset, 512); offset += tempLen; } byte[] bytesToSave = new byte[offset]; for (int i = 0; i < offset; i++) { bytesToSave[i] = infbytes[i]; } File.WriteAllBytes(saveFileName, bytesToSave); //直接一次读取 //tempLen = ReceiveStream.Read(infbytes, 0, 20480); //byte[] bytesToSave = new byte[tempLen]; //for (int i = 0; i < tempLen; i++) //{ // bytesToSave[i] = infbytes[i]; //} //File.WriteAllBytes(System.Windows.Forms.Application.StartupPath + "\\dataToDown\\" + "mydata", bytesToSave); re = "保存至文件" + saveFileName; } catch (WebException wex) { if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { re = "StatusCode: " + Convert.ToInt32(((HttpWebResponse)wex.Response).StatusCode) + "\r\n"; using (var reader = new StreamReader(errorResponse.GetResponseStream())) { re += reader.ReadToEnd(); } } } else { re = wex.Message; } } catch (Exception ex) { re = "Unknow Error"; ErrorLog.PutInLog("ID:1096 " + ex.Message); } if (myWatch.IsRunning) { myWatch.Stop(); } myEdr.spanTime = myWatch.ElapsedMilliseconds.ToString(); myEdr.backContent = re; return(re); }
/// <summary> /// i will Send Data /// </summary> /// <param name="url"> url </param> /// <param name="data"> param </param> /// <param name="method">GET/POST</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <param name="saveFileName">the file will save with this name</param> /// <returns>back</returns> public static string SendData(string url, string data, string method, List <KeyValuePair <string, string> > heads, MyExecutionDeviceResult myEdr, string saveFileName) { string re = ""; bool hasBody = !string.IsNullOrEmpty(data); bool needBody = method.ToUpper() == "POST" || method.ToUpper() == "PUT"; Stopwatch myWatch = new Stopwatch(); try { //except POST other data will add the url,if you want adjust the ruleschange here if (method.ToUpper() != "POST" && data != null) { url += "?" + data; data = null; } string tempUrl = url; //由于下载限制,实际对于需要下载大文件的请求,也使用的是GET if (!needBody && hasBody) { tempUrl = tempUrl + "?" + data; } myEdr.startTime = DateTime.Now.ToString("HH:mm:ss"); using (WebClient client = new WebClient()) { MyWebTool.HttpHelper.AddHttpHeads(client.Headers, heads); myWatch.Start(); client.DownloadFile(tempUrl, saveFileName); myWatch.Stop(); } re = "保存至文件" + saveFileName; } catch (WebException wex) { if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { re = "StatusCode: " + Convert.ToInt32(((HttpWebResponse)wex.Response).StatusCode) + "\r\n"; using (var reader = new StreamReader(errorResponse.GetResponseStream())) { re += reader.ReadToEnd(); } } } else { re = wex.Message; } } catch (Exception ex) { re = "Unknow Error"; ErrorLog.PutInLog("ID:1174 " + ex.Message); } if (myWatch.IsRunning) { myWatch.Stop(); } myEdr.spanTime = myWatch.ElapsedMilliseconds.ToString(); myEdr.backContent = re; return(re); }
/// <summary> /// i will Send Data with multipart,if you do not want updata any file you can set isFile is false and set filePath is null /// </summary> /// <param name="url">url</param> /// <param name="timeOut">timeOut</param> /// <param name="name">Parameter name</param> /// <param name="filename">filename</param> /// <param name="isFile">is a file</param> /// <param name="filePath">file path or cmd</param> /// <param name="bodyParameter">the other Parameter in body</param> /// <param name="myAht">the myAutoHttpTest will fill the data</param> /// <returns>back</returns> public static string HttpPostData(string url, int timeOut, string name, string filename, bool isFile, string filePath, string bodyParameter, MyExecutionDeviceResult myEdr) { string responseContent = null; NameValueCollection stringDict = new NameValueCollection(); if (bodyParameter != null) { string[] sArray = bodyParameter.Split('&'); foreach (string tempStr in sArray) { int myBreak = tempStr.IndexOf('='); if (myBreak == -1) { myEdr.backContent = "can't find ="; return("can't find ="); } stringDict.Add(tempStr.Substring(0, myBreak), tempStr.Substring(myBreak + 1)); } } var memStream = new MemoryStream(); var webRequest = (HttpWebRequest)WebRequest.Create(url); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); // 边界符 var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = timeOut; //是否带文件提交 if (filePath != null) { webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // 写入文件 const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, name, filename); var headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); if (isFile) { try { using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; int bytesRead; // =0 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } } } catch (Exception ex) { responseContent = "Error: " + ex.Message + "\r\n"; ErrorLog.PutInLog("ID:0544 " + ex.InnerException); myEdr.backContent = responseContent; return(responseContent); } } else { byte[] myCmd = Encoding.UTF8.GetBytes(filePath); memStream.Write(myCmd, 0, myCmd.Length); } } //写入POST非文件参数 if (bodyParameter != null) { //写入字符串的Key var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}"; for (int i = 0; i < stringDict.Count; i++) { try { byte[] formitembytes = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, stringDict.GetKey(i), stringDict.Get(i))); memStream.Write(formitembytes, 0, formitembytes.Length); } catch (Exception ex) { return("can not send :" + ex.Message); } } memStream.Write(Encoding.ASCII.GetBytes("\r\n"), 0, Encoding.ASCII.GetBytes("\r\n").Length); } else { memStream.Write(Encoding.ASCII.GetBytes("\r\n"), 0, Encoding.ASCII.GetBytes("\r\n").Length); } //写入最后的结束边界符 //memStream.Write(Encoding.ASCII.GetBytes("\r\n"), 0, Encoding.ASCII.GetBytes("\r\n").Length); memStream.Write(endBoundary, 0, endBoundary.Length); webRequest.ContentLength = memStream.Length; Stopwatch myWatch = new Stopwatch(); myEdr.startTime = DateTime.Now.ToString("HH:mm:ss"); myWatch.Start(); //开始请求 try { var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { if (showResponseHeads) { responseContent = httpWebResponse.Headers.ToString(); } responseContent = httpStreamReader.ReadToEnd(); } myWatch.Stop(); httpWebResponse.Close(); webRequest.Abort(); } catch (WebException wex) { responseContent = ""; if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { responseContent = "StatusCode: " + Convert.ToInt32(((HttpWebResponse)wex.Response).StatusCode) + "\r\n"; using (var reader = new StreamReader(errorResponse.GetResponseStream())) { responseContent += reader.ReadToEnd(); } } } else { responseContent = wex.Message; } } catch (Exception ex) { responseContent = "Error: " + ex.Message + "\r\n"; ErrorLog.PutInLog("ID:0090 " + ex.InnerException); } if (myWatch.IsRunning) { myWatch.Stop(); } myEdr.spanTime = myWatch.ElapsedMilliseconds.ToString(); myEdr.backContent = responseContent; return(responseContent); }