/// <summary> /// 傳入卡號,去後台AP檢查有效性(port:6103) /// 000000:Pass/990001:後台錯誤/990003:黑名單/990012:非有效卡或非聯名卡或非正常卡 /// </summary> /// <param name="icc_No"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <returns>Return Code(若傳輸異常回傳null)</returns> public string CheckCard(string icc_No,string ip,int port = 6103) { AL2POS_Domain queryObj = new AL2POS_Domain() { ICC_NO = icc_No, READER_ID = string.Empty, REG_ID = string.Empty, STORE_NO = string.Empty, AL_AMT = 0, }; string queryStr = JsonConvert.SerializeObject(queryObj); byte[] queryRequest = Encoding.UTF8.GetBytes(queryStr); byte[] queryResponse; using (SocketClient.Domain.SocketClient client = new SocketClient.Domain.SocketClient(ip,port)) { queryResponse = client.SendAndReceive(queryRequest); } if (queryResponse != null) { string responseStr = Encoding.UTF8.GetString(queryResponse); AL2POS_Domain response = JsonConvert.DeserializeObject<AL2POS_Domain>(responseStr); return response.AL2POS_RC; } else { return null; } }
/// <summary> /// 送出沖正Txlog request到後台並取回 沖正Txlog response /// </summary> /// <param name="request"></param> /// <returns></returns> protected override ALTxlog_Domain GetResponse(ALTxlog_Domain request) { ALTxlog_Domain result = null; SocketClient.Domain.SocketClient socketClient = null; try { System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); SocketClient.Domain.Utilities.NewJsonWorker <ALTxlog_Domain> jsonWorker = new SocketClient.Domain.Utilities.NewJsonWorker <ALTxlog_Domain>(); byte[] dataByte = jsonWorker.Serialize2Bytes(request); log.Debug(m => m("3.[AutoLoadReversalTxLog][Send] to Back-End Data: {0}", Encoding.ASCII.GetString(dataByte))); string[] setting = ConfigLoader.GetSetting(ConType.AutoLoadReversalTxLog).Split(':'); string ip = setting[0]; int port = Convert.ToInt32(setting[1]); int sendTimeout = Convert.ToInt32(setting[2]); int receiveTimeout = Convert.ToInt32(setting[3]); timer.Start(); socketClient = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout); if (socketClient.ConnectToServer()) { byte[] resultBytes = null; resultBytes = socketClient.SendAndReceive(dataByte); timer.Stop(); log.Debug(m => m("4.[AutoLoadReversalTxLog][Receive]Back-End Response(TimeSpend:{1}ms): {0}", Encoding.ASCII.GetString(resultBytes), timer.ElapsedMilliseconds)); result = jsonWorker.Deserialize(resultBytes); } return(result); } catch (SocketException sckEx) { log.Error("[GetResponse]Send Back-End Socket Error: " + sckEx.Message + " \r\n" + sckEx.StackTrace); return(null); } catch (Exception ex) { log.Error("[GetResponse]Send Back-End Error: " + ex.Message + " \r\n" + ex.StackTrace); return(null); } finally { if (socketClient != null) { socketClient.CloseConnection(); } } }
/// <summary> /// 送出沖正Txlog request到後台並取回 沖正Txlog response /// </summary> /// <param name="request"></param> /// <returns></returns> protected override ALTxlog_Domain GetResponse(ALTxlog_Domain request) { ALTxlog_Domain result = null; SocketClient.Domain.SocketClient socketClient = null; try { System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); SocketClient.Domain.Utilities.NewJsonWorker<ALTxlog_Domain> jsonWorker = new SocketClient.Domain.Utilities.NewJsonWorker<ALTxlog_Domain>(); byte[] dataByte = jsonWorker.Serialize2Bytes(request); log.Debug(m => m("3.[AutoLoadReversalTxLog][Send] to Back-End Data: {0}", Encoding.ASCII.GetString(dataByte))); string[] setting = ConfigLoader.GetSetting(ConType.AutoLoadReversalTxLog).Split(':'); string ip = setting[0]; int port = Convert.ToInt32(setting[1]); int sendTimeout = Convert.ToInt32(setting[2]); int receiveTimeout = Convert.ToInt32(setting[3]); timer.Start(); socketClient = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout); if (socketClient.ConnectToServer()) { byte[] resultBytes = null; resultBytes = socketClient.SendAndReceive(dataByte); timer.Stop(); log.Debug(m => m("4.[AutoLoadReversalTxLog][Receive]Back-End Response(TimeSpend:{1}ms): {0}", Encoding.ASCII.GetString(resultBytes), timer.ElapsedMilliseconds)); result = jsonWorker.Deserialize(resultBytes); } return result; } catch (SocketException sckEx) { log.Error("[GetResponse]Send Back-End Socket Error: " + sckEx.Message + " \r\n" + sckEx.StackTrace); return null; } catch (Exception ex) { log.Error("[GetResponse]Send Back-End Error: " + ex.Message + " \r\n" + ex.StackTrace); return null; } finally { if (socketClient != null) { socketClient.CloseConnection(); } } }
private void StartConmunicate() { string ip = this.IP.Text; int port = (int)this.Port.Value; byte[] receiveData = null; byte[] sendData = this.StringToByteArray(this.RequestHex.Text); try { using (SocketClient.Domain.SocketClient client = new SocketClient.Domain.SocketClient(ip, port)) { timer.Restart(); if (client.ConnectToServer()) { receiveData = client.SendAndReceive(sendData); string result = String.Format("Receive Data(byte length:{0}): {1}", receiveData.Length, BitConverter.ToString(receiveData).Replace("-", "")); this.ResponseHex.Text = result; this.ReturnCode.Text = MsgContainer.ALQRespMsgUtility.GetStr(receiveData, "ReturnCode"); } } } catch (SocketException sckEx) { MessageBox.Show(String.Format("Socket 異常:{0}", sckEx.Message)); this.ResponseHex.Text = string.Empty; } catch (Exception ex) { MessageBox.Show(String.Format("一般異常:{0}", ex.Message)); this.ResponseHex.Text = string.Empty; } finally { timer.Stop(); this.TimeSpend.Text = this.timer.ElapsedMilliseconds.ToString(); this.SendRequest.Enabled = true; } }
public void RunBatch() { byte[] receiveBytes = null; SocketClient.Domain.SocketClient bankAgent = null; AutoloadRqt_2Bank requestToBank = null; AutoloadRqt_2Bank responseFormBank = null; //建立DB模組 AL_DBModule obDB = new AL_DBModule(); //交易log模組 LogModual logM = new LogModual(); try { //初始化DicBankAgents集合 this.InitBankAgentSetting(); //開啟連線 obDB.OpenConnection(); //-------------------------------------------------------------------------------------------- //從字典取出每個要傳批次的電文類型 foreach (BankAgent item in this.DicBankAgents.Keys) { log.Debug("開始檢查" + item.BankCode + "銀行的狀態與MQ存放的" + item.MessageType + "資料"); #region 1.當銀行狀態是連線的且MQ有傳資料(Ex:0120類型)回來(放在工作Queue) while (this.DicBanks[item.BankCode].STATUS == "0" && this.DicBankAgents[item].synTopicSubscriber.Process()) { if (this.waitForWork.Count == 0) { log.Error("待辦工作Queue[waitForWork]內無資料"); break; } DateTime dtrqt = DateTime.Now; DateTime dtrsp = DateTime.Now; string requestToBankJsonStr = this.waitForWork.Dequeue();//取得要傳送的字串 try { using (bankAgent = new SocketClient.Domain.SocketClient(item.IP, item.Port, item.SendTimeout, item.ReceiveTimeout)) { if (bankAgent.ConnectToServer()) { log.Debug("送到" + item.IP + ":" + item.Port + "的資料: " + requestToBankJsonStr); byte[] sendJsonBytes = Encoding.UTF8.GetBytes(requestToBankJsonStr); receiveBytes = bankAgent.SendAndReceive(sendJsonBytes);//送出資料並取得回應資料 if (receiveBytes == null) { log.Debug("接收資料為null,開始將資料加入異常Queue"); //要用Regex來比對嗎 Performance不知好不好//MESSAGE_TYPE:XXX0 --> XXX1 if (Regex.IsMatch(requestToBankJsonStr, "^{\"MESSAGE_TYPE\":\"[0-9]{3}0")) { string repeatRequest = Regex.Replace(requestToBankJsonStr, "^{\"MESSAGE_TYPE\":\"[0-9]{3}0", delegate(Match match) { string result = match.Value.Substring(0, match.Value.Length - 1) + "1"; //xxx0 --> xxx1 return(result); }); log.Debug("送出失敗: 修改MESSAGE_TYPE後的JSON =>" + repeatRequest); //轉型回物件改MESSAGE_TYPE屬性內的值 //AutoloadRqt_2Bank tmp = JsonConvert.DeserializeObject<AutoloadRqt_2Bank>(requestToBankJsonStr); //tmp.MESSAGE_TYPE = tmp.MESSAGE_TYPE.Substring(0, 3) + "1";// //string sendFailRequest = JsonConvert.SerializeObject(tmp); this.failed.Enqueue(repeatRequest); } else { //MESSAGE_TYPE:XXX1//格式已是重送的SPEC this.failed.Enqueue(requestToBankJsonStr);//加入異常列表 } continue; } } } } catch (Exception ex) { log.Error("連線BankAgent異常:" + ex.StackTrace); log.Error("連線異常,開始將資料加入異常Queue"); //只修改第一層message_type的data,第二層message_type的data不動(因為第二層為原始交易資訊) string repeatRequest = Regex.Replace(requestToBankJsonStr, "^{\"MESSAGE_TYPE\":\"[0-9]{3}0", delegate(Match match) { string result = match.Value.Substring(0, match.Value.Length - 1) + "1"; return(result); }); log.Debug("[Exception]: 修改MESSAGE_TYPE後的JSON =>" + repeatRequest); this.failed.Enqueue(repeatRequest);//加入異常列表 continue; } finally { //寫送出的Tans Log //轉型 requestToBank = JsonConvert.DeserializeObject <AutoloadRqt_2Bank>(requestToBankJsonStr); dtrsp = DateTime.Now; //給銀行需要12碼,給DB紀錄只能8碼,故金額切掉多餘的碼(剩8碼) requestToBank.AMOUNT = (requestToBank.AMOUNT.Length > 8) ? requestToBank.AMOUNT.Substring(requestToBank.AMOUNT.Length - 8, 8) : requestToBank.AMOUNT; //記錄此次交易 log.Debug("[紀錄]給銀行的JSON:" + requestToBankJsonStr); log.Debug("開始寫入Log傳給銀行的Request物件(類型:" + requestToBank.MESSAGE_TYPE + ")"); logM.SaveTransLog2Bank(requestToBank, obDB, dtrqt, dtrsp); } //回傳訊息不為空 if (receiveBytes != null) { try { //寫接收的Tans Log //轉型 string responseFormBankJsonStr = Encoding.UTF8.GetString(receiveBytes); responseFormBank = JsonConvert.DeserializeObject <AutoloadRqt_2Bank>(responseFormBankJsonStr); //記錄此次交易 log.Debug("[紀錄]銀行回來的的JSON:" + responseFormBankJsonStr); log.Debug("開始寫入Log銀行回傳的Response物件(類型:" + responseFormBank.MESSAGE_TYPE + ")"); //因為銀行回傳無Field 61,所以從給銀行的POCO取 responseFormBank.ICC_info = requestToBank.ICC_info; //截掉銀行的代碼(DB只能3碼)-DB可以容許5碼_2015-04-28 //rspFromBank.BANK_CODE = rspFromBank.BANK_CODE.Substring((rspFromBank.BANK_CODE.Length - 3), 3); //銀行回應的有12碼,給DB紀錄只能8碼,故金額切掉多餘的碼(剩8碼) responseFormBank.AMOUNT = (responseFormBank.AMOUNT.Length > 8) ? responseFormBank.AMOUNT.Substring(responseFormBank.AMOUNT.Length - 8, 8) : responseFormBank.AMOUNT; dtrsp = DateTime.Now; logM.SaveTransLog2Bank(responseFormBank, obDB, dtrqt, dtrsp); } catch (Exception ex2) { logM.SaveErrorLog(obDB, this.GetType().Name + ex2.Message, "BatchAP"); log.Error("[BatchAP][RunBatch] Save Bank Trans Log Failed: " + ex2.StackTrace); } } bankAgent = null; } #endregion #region 2.將異常列表的資料塞回MQ log.Debug("2.開始將異常列表的資料塞回MQ=>筆數:" + this.failed.Count); this.DicBankAgents[item].topicPublisher.Start(); int count = 1; while (this.failed.Count > 0) { //從異常Queue取出送到銀行端失敗的Json String string backToMQJsonStr = this.failed.Dequeue(); log.Debug("開始發佈第 " + (count++) + " 筆發送失敗的POCO到MQ: " + backToMQJsonStr); //發佈回MQ this.DicBankAgents[item].topicPublisher.SendMessage <string>(backToMQJsonStr); } #endregion #region 3.清空Queue log.Debug("開始檢查並清空" + item.MessageType + "格式的暫存Queue"); if (this.waitForWork.Count > 0 || this.failed.Count > 0) { log.Debug("見鬼了...(類型:" + item.MessageType + ")Queue還有東西:\n waitForWork:" + this.waitForWork.Count + " \nfailed:" + this.failed.Count); } this.waitForWork.Clear(); this.failed.Clear(); #endregion } } catch (Exception ex) { log.Error("[BatchAP][RunBatch] Error:" + ex.StackTrace); } finally { receiveBytes = null; requestToBank = null; responseFormBank = null; obDB.CloseConnection(); } }
/// <summary> /// Send Reuqest POCO to Center AP and receive response POCO /// </summary> /// <param name="request">自動加值請求物件</param> /// <returns>自動加值回應物件</returns> private ALTxlog_Domain SendAndReceiveFromAP(ALTxlog_Domain request, string serviceName) { ALTxlog_Domain response = null; string requestStr = null; byte[] requestBytes = null; string responseString = null; byte[] responseBytes = null; string serverConfig = null; string ip = null; int port = -1; int sendTimeout = -1; int receiveTimeout = -1; string[] configs = null; //********************************* //取得連線後台的WebConfig設定資料 serverConfig = ConfigGetter.GetValue(serviceName); log.Debug(m => { m.Invoke(serviceName + ":" + serverConfig); }); if (serverConfig != null) { configs = serverConfig.Split(':'); ip = configs[0]; port = Convert.ToInt32(configs[1]); sendTimeout = Convert.ToInt32(configs[2]); receiveTimeout = Convert.ToInt32(configs[3]); } else { log.Error("要連結的目的地設定資料不存在:" + serviceName); return null; } //********************************* try { using (SocketClient.Domain.SocketClient connectToAP = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout)) { log.Debug("開始連線後端服務:" + serverConfig); if (connectToAP.ConnectToServer()) { //UTF8(JSON(POCO))=>byte array and send to AP requestStr = JsonConvert.SerializeObject(request); log.Debug(m => m("[AutoLoadTxLog]Request JsonString({0}): {1}", serverConfig, requestStr)); requestBytes = Encoding.UTF8.GetBytes(requestStr);//Center AP used UTF8 responseBytes = connectToAP.SendAndReceive(requestBytes); if (responseBytes != null) { responseString = Encoding.UTF8.GetString(responseBytes); response = JsonConvert.DeserializeObject<ALTxlog_Domain>(responseString); } log.Debug(m => { m.Invoke("[AutoLoadTxLog]Response JsonString: {0}", ((responseBytes == null) ? "null" : responseString)); }); } } } catch (Exception ex) { log.Error(m => m("後台({0})連線異常:{1}", serverConfig, ex.Message)); } return response; }
/// <summary> /// 連線後端AP並取得output data /// </summary> /// <param name="request"></param> /// <returns></returns> private static EskmsKeyPOCO GetResponse(EskmsKeyPOCO request) { string requestStr = null; byte[] requestBytes = null; string responseStr = null; byte[] responseBytes = null; string ip = null; int port = -1; int sendTimeout = -1; int receiveTimeout = -1; string serverConfig = null; string[] configs = null; EskmsKeyPOCO response = null; //********************************* //取得連線後台的WebConfig設定資料 serverConfig = ConfigGetter.GetValue(ServiceName); log.Debug(m => { m.Invoke(ServiceName + ":" + serverConfig); }); if (serverConfig != null) { configs = serverConfig.Split(':'); ip = configs[0]; port = Convert.ToInt32(configs[1]); sendTimeout = Convert.ToInt32(configs[2]); receiveTimeout = Convert.ToInt32(configs[3]); } else { log.Error("要連結的目的地設定資料不存在:" + ServiceName); return null; } //********************************* try { using (SocketClient.Domain.SocketClient connectToAP = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout)) { log.Debug("開始連線後端服務:" + serverConfig); if (connectToAP.ConnectToServer()) { //UTF8(JSON(POCO))=>byte array and send to AP requestStr = JsonConvert.SerializeObject(request); log.Debug(m => m("[ReaderShipmentHandler]Request JsonString({0}): {1}", ServiceName, requestStr)); requestBytes = Encoding.UTF8.GetBytes(requestStr);//Center AP used UTF8 responseBytes = connectToAP.SendAndReceive(requestBytes); if (responseBytes != null) { responseStr = Encoding.UTF8.GetString(responseBytes); response = JsonConvert.DeserializeObject<EskmsKeyPOCO>(responseStr); //Byte[] 會被JSON轉成Base64格式 log.Debug(m => { m.Invoke("[ReaderShipmentHandler]Response JsonString:\n DiversKey:{0}", BitConverter.ToString(response.Output_DiversKey).Replace("-", "")); }); } else { //Byte[] 會被JSON轉成Base64格式 log.Debug(m => { m.Invoke("[ReaderShipmentHandler]Response JsonString: null"); }); } } } } catch (Exception ex) { log.Error("後台連線異常:" + ex.Message); } return response; }
/// <summary> /// 連線後端AP並取得output data /// </summary> /// <param name="request"></param> /// <returns></returns> private static EskmsKeyPOCO GetResponse(EskmsKeyPOCO request) { string requestStr = null; byte[] requestBytes = null; string responseStr = null; byte[] responseBytes = null; string ip = null; int port = -1; int sendTimeout = -1; int receiveTimeout = -1; string serverConfig = null; string[] configs = null; EskmsKeyPOCO response = null; //********************************* //取得連線後台的WebConfig設定資料 serverConfig = ConfigGetter.GetValue(ServiceName); log.Debug(m => { m.Invoke(ServiceName + ":" + serverConfig); }); if (serverConfig != null) { configs = serverConfig.Split(':'); ip = configs[0]; port = Convert.ToInt32(configs[1]); sendTimeout = Convert.ToInt32(configs[2]); receiveTimeout = Convert.ToInt32(configs[3]); } else { log.Error("要連結的目的地設定資料不存在:" + ServiceName); return(null); } //********************************* try { using (SocketClient.Domain.SocketClient connectToAP = new SocketClient.Domain.SocketClient(ip, port, sendTimeout, receiveTimeout)) { log.Debug("開始連線後端服務:" + serverConfig); if (connectToAP.ConnectToServer()) { //UTF8(JSON(POCO))=>byte array and send to AP requestStr = JsonConvert.SerializeObject(request); log.Debug(m => m("[ReaderShipmentHandler]Request JsonString({0}): {1}", ServiceName, requestStr)); requestBytes = Encoding.UTF8.GetBytes(requestStr);//Center AP used UTF8 responseBytes = connectToAP.SendAndReceive(requestBytes); if (responseBytes != null) { responseStr = Encoding.UTF8.GetString(responseBytes); response = JsonConvert.DeserializeObject <EskmsKeyPOCO>(responseStr); //Byte[] 會被JSON轉成Base64格式 log.Debug(m => { m.Invoke("[ReaderShipmentHandler]Response JsonString:\n DiversKey:{0}", BitConverter.ToString(response.Output_DiversKey).Replace("-", "")); }); } else { //Byte[] 會被JSON轉成Base64格式 log.Debug(m => { m.Invoke("[ReaderShipmentHandler]Response JsonString: null"); }); } } } } catch (Exception ex) { log.Error("後台連線異常:" + ex.Message); } return(response); }
private void StartConmunicate() { string ip = this.IP.Text; int port = (int)this.Port.Value; byte[] receiveData = null; byte[] sendData = this.StringToByteArray(this.RequestHex.Text); try { using (SocketClient.Domain.SocketClient client = new SocketClient.Domain.SocketClient(ip, port)) { timer.Restart(); if (client.ConnectToServer()) { receiveData = client.SendAndReceive(sendData); string result = String.Format("Receive Data(byte length:{0}): {1}", receiveData.Length, BitConverter.ToString(receiveData).Replace("-", "")); this.ResponseHex.Text = result; this.ReturnCode.Text = MsgContainer.ALQRespMsgUtility.GetStr(receiveData, "ReturnCode"); } } } catch (SocketException sckEx) { MessageBox.Show(String.Format("Socket 異常:{0}", sckEx.Message)); this.ResponseHex.Text = string.Empty; } catch (Exception ex) { MessageBox.Show(String.Format("一般異常:{0}", ex.Message)); this.ResponseHex.Text = string.Empty; } finally { timer.Stop(); this.TimeSpend.Text = this.timer.ElapsedMilliseconds.ToString(); this.SendRequest.Enabled = true; } }