public SendResult(SendStatus sendStatus, long messageOffset, MessageQueue messageQueue, long queueOffset) { SendStatus = sendStatus; MessageOffset = messageOffset; MessageQueue = messageQueue; QueueOffset = queueOffset; }
public WhenTransferringMultipartMessages() { SenderAction = req => { SendResult1 = SendResult2 = req.SendMessage(new ZmqMessage(new[] { Messages.MultiFirst, Messages.MultiLast })); }; ReceiverAction = rep => { Message = rep.ReceiveMessage(); }; }
public void OnSent(INetworkClient client, SendStatus status) { switch (status) { case SendStatus.SUCCESS: Debug.WriteLine("SEND Success"); break; case SendStatus.FAIL_CONNECTION_CLOSING: Debug.WriteLine("SEND failed due to connection closing"); break; case SendStatus.FAIL_INVALID_PACKET: Debug.WriteLine("SEND failed due to invalid socket"); break; case SendStatus.FAIL_NOT_CONNECTED: Debug.WriteLine("SEND failed due to no connection"); break; case SendStatus.FAIL_SOCKET_ERROR: Debug.WriteLine("SEND Socket Error"); break; } }
public WhenSubscribingToASpecificPrefix() { _signal = new ManualResetEvent(false); ReceiverInit = sub => sub.Subscribe(Messages.PubSubPrefix); ReceiverAction = sub => { _signal.Set(); _message1 = sub.ReceiveFrame(); _message2 = sub.ReceiveFrame(TimeSpan.FromMilliseconds(500)); }; SenderInit = pub => _signal.WaitOne(1000); SenderAction = pub => { _sendResult1 = pub.SendFrame(Messages.PubSubFirst); _sendResult2 = pub.SendFrame(Messages.PubSubSecond); }; }
public HtsExtractSentEvent(List <Guid> sentIds, SendStatus status, string extract, string statusInfo = "") { SentItems = sentIds.Select(x => new SentItem(x, status, statusInfo, extract)).ToList(); }
/// <summary> /// Send callback /// </summary> /// <param name="socket">client socket</param> /// <param name="status">stend status</param> /// <param name="sentPacket">sent packet</param> public void OnSent(INetworkSocket socket, SendStatus status, Packet sentPacket) { }
public static void SendQueuedSMS(int failureInterval, int maxNumberOfTries, SiteSettings settings) { ErrorLog.Write("开始发送短信,进入队列..."); if (settings != null) { HiConfiguration config = HiConfiguration.GetConfig(); Dictionary <System.Guid, SmsInfo> dictionary = new SMSQueueDao().DequeueSMS(); IList <System.Guid> list = new List <System.Guid>(); ErrorLog.Write("开始发送短信,创建发送对象..."); SMSSender sender = Messenger.CreateSMSSender(settings); if (sender != null) { int num = 0; int smsSendBatchSize = 500; foreach (System.Guid current in dictionary.Keys) { SmsInfo currentSms = dictionary[current]; string msg = ""; SendStatus sendStatus = SendStatus.Fail; try { ErrorLog.Write(string.Format("发送短信,手机号码:{0},短信内容:{1}", currentSms.Mobile, currentSms.Body)); if (currentSms.type == 2) { sendStatus = Messenger.SendSMS(currentSms.Mobile, currentSms.Body, settings, currentSms.type, out msg); } else { sendStatus = Messenger.SendSMS(currentSms.Mobile, currentSms.Body, settings, out msg); } } catch (Exception ex) { ErrorLog.Write(string.Format("发送短信异常,手机号码:{0},短信内容:{1},原因:{2}", currentSms.Mobile, currentSms.Body, ex.Message)); } if (sendStatus == SendStatus.Success) { ErrorLog.Write(string.Format("发送短信成功,开始删除队列,手机号码:{0},短信内容:{1}", currentSms.Mobile, currentSms.Body)); new SMSQueueDao().DeleteQueuedSMS(current); if (smsSendBatchSize != -1 && ++num >= smsSendBatchSize) { System.Threading.Thread.Sleep(new System.TimeSpan(0, 0, 0, 15, 0)); num = 0; } } else { ErrorLog.Write(string.Format("发送短信失败,手机号码:{0},短信内容:{1},加入失败队列", currentSms.Mobile, currentSms.Body)); list.Add(current); } } if (list.Count > 0) { ErrorLog.Write("发送短信包含失败号码,重置发送队列"); new SMSQueueDao().QueueSendingFailure(list, failureInterval, maxNumberOfTries); } } else { ErrorLog.Write("开始发送短信,发送对象创建不成功,请检查配置..."); } } }
private bool CannotBeRetried(SendStatus status) { return(status == SendStatus.Success || status == SendStatus.NoExchangeFound || status == SendStatus.Unroutable); }
/// <summary> /// 受信処理 /// </summary> protected void recvTask() { int bytesToRead = 0; switch (recvStatus) { case RecvStatus.Ready: // バイト数チェック try { bytesToRead = serialPort.BytesToRead; if (bytesToRead < 1) { return; } // ヘッダチェック read(buffer, 0, 1); } catch { ts.TraceInformation("readで例外発生"); return; } // 受信ヘッダチェック if (CommandUtil.CheckHeader(buffer) == false) { ts.TraceInformation("受信ヘッダチェック異常"); return; } recvStatus = RecvStatus.HeaderReading; break; case RecvStatus.HeaderReading : // バイト数チェック try { bytesToRead = serialPort.BytesToRead; if (bytesToRead < 1) { return; } // ヘッダチェック read(buffer, 1, 1); } catch { ts.TraceInformation("readで例外発生"); return; } recvStatus = RecvStatus.CommandProcessing; break; case RecvStatus.CommandProcessing: // 本文チェック byte bodyLength = buffer[1]; try { // 本文の長さ以上のデータが読み込めれば続行する。 bytesToRead = serialPort.BytesToRead; if (bytesToRead < bodyLength+2) { return; } // 本文読み込み read(buffer, 2, bodyLength + 2); // コマンドをデコードする byte[] byteImage = new byte[bodyLength + 4]; Array.Copy(buffer, byteImage, bodyLength + 4); recvCommand = CommandUtil.decodeCommand(byteImage); // Ackを受信した場合 if (recvCommand.Cmd == 'w' || recvCommand.Cmd == 'r') { // 状態異常時 if (sendStatus != SendStatus.AckWaiting) { ts.TraceInformation("AckWaiting以外でAckを受け取ったため無視します。"); } // 正常時 else { sendStatus = SendStatus.CommandProcessing; sendAckCommand = recvCommand.Clone(); } } // Ack以外のコマンドを受信した場合 else { // コマンド実行 execCommand(recvCommand); // Ackの返信 respondAck(recvCommand); } } catch { ts.TraceInformation("コマンド受信異常"); } // シーケンスを終了 recvStatus = RecvStatus.Ready; break; } }
/// <summary> /// Send callback /// </summary> /// <param name="socket">client socket</param> /// <param name="status">stend status</param> /// <param name="sentPacket">sent packet</param> public void OnParallelSocketSent(IParallelSocket socket, SendStatus status, ParallelPacket sentPacket) { string sentString = ASCIIEncoding.ASCII.GetString(sentPacket.CloneData()); Debug.Print("Sent [" + sentPacket.PacketID + "] " + sentString); }
private void ClientThread(object contextObj) { var context = (ZmqContext)contextObj; using (var socket = context.CreateSocket(SocketType.REQ)) { _readyEvent.WaitOne(); socket.Connect("tcp://localhost:9000"); Console.WriteLine("Receive(Frame)"); foreach (int messageSize in MessageSizes) { var msg = new Frame(messageSize); var reply = new Frame(messageSize); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < RoundtripCount; i++) { SendStatus sendStatus = socket.SendFrame(msg); Debug.Assert(sendStatus == SendStatus.Sent, "Message was not indicated as sent."); reply = socket.ReceiveFrame(reply); Debug.Assert(reply.MessageSize == messageSize, "Pong message did not have the expected size."); } watch.Stop(); long elapsedTime = watch.ElapsedTicks; Console.WriteLine("Message size: " + messageSize + " [B]"); Console.WriteLine("Roundtrips: " + RoundtripCount); double latency = (double)elapsedTime / RoundtripCount / 2 * 1000000 / Stopwatch.Frequency; Console.WriteLine("Your average latency is {0} [us]", latency.ToString("f2")); } Console.WriteLine("Receive(byte[])"); foreach (int messageSize in MessageSizes) { var msg = new Frame(messageSize); var reply = new byte[messageSize]; var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < RoundtripCount; i++) { SendStatus sendStatus = socket.SendFrame(msg); Debug.Assert(sendStatus == SendStatus.Sent, "Message was not indicated as sent."); int bytesReceived = socket.Receive(reply); Debug.Assert(bytesReceived == messageSize, "Pong message did not have the expected size."); } watch.Stop(); long elapsedTime = watch.ElapsedTicks; Console.WriteLine("Message size: " + messageSize + " [B]"); Console.WriteLine("Roundtrips: " + RoundtripCount); double latency = (double)elapsedTime / RoundtripCount / 2 * 1000000 / Stopwatch.Frequency; Console.WriteLine("Your average latency is {0} [us]", latency.ToString("f2")); } } }
private static IMessageSender CreateMessageSenderMock(MessageSenderType senderType, SendStatus statusToReturn) { var messageSenderMock = A.Fake <IMessageSender>(); A.CallTo(() => messageSenderMock.SenderType).Returns(senderType); A.CallTo(() => messageSenderMock.Send(A <User> .Ignored, A <string> .Ignored)).Returns(statusToReturn); return(messageSenderMock); }
/// <summary> /// Creates an instance of SendAsyncCompletedEventArgs. /// </summary> /// <param name="status"></param> public SendAsyncCompletedEventArgs(SendStatus status) { Status = status; }
/// <summary> /// Sets the status of the specified send to the specified status. /// </summary> /// <param name="sendID">ID of the send to set the staus of.</param> /// <param name="status">The status to set the send to.</param> internal void SetSendStatus(string sendID, SendStatus status) { SendDB.SetSendStatus(sendID, status); }
public SendResult(SendStatus sendStatus, MessageStoreResult messageStoreResult, string errorMessage) { SendStatus = sendStatus; MessageStoreResult = messageStoreResult; ErrorMessage = errorMessage; }
public SendResult(SendStatus sendStatus, SendMessageResponse messageResult, string errorMessage) { SendStatus = sendStatus; MessageResult = messageResult; ErrorMessage = errorMessage; }
/// <summary> /// Protokolliert die Weiterleitung einer Nachricht /// </summary> /// <param name="contentId">Id für den Inhalt (Text) der Nachricht</param> /// <param name="sentToId">Id für den Empfänger der Nachricht</param> /// <param name="sendVia">Sendeweg 1 = SMS, 2 = Email</param> /// <param name="smsReference">Index aus GSM Modem bei SMS</param> /// <param name="confirmStatus">Statuscode 0=Eintrag erstellt, 1=Versendet, 2=Warten auf Sendebericht, 4=Nochmal senden, 8=Senden abgebrochen, 16=senden erfolgreich</param> /// <returns></returns> private int InsertMessageSent(int contentId, int sentToId, SendWay sendVia, int smsReference, SendStatus confirmStatus = 0) { try { const string query = "INSERT INTO \"LogSent\" (\"SentToId\", \"ContentId\", \"SentVia\", \"SmsRef\", \"ConfirmStatus\" ) " + "VALUES (@sentToId, @contentId, @sendVia, @smsRef, @confirmStatus);" + "SELECT Id FROM \"LogSent\" ORDER BY \"SentTime\" DESC LIMIT 1"; Dictionary<string, object> args = new Dictionary<string, object> { { "@sentToId", sentToId }, { "@contentId", contentId }, { "@sendVia", sendVia }, { "@smsRef", smsReference }, { "@confirmStatus", confirmStatus } }; return SqlSelectInteger(query, args); } catch (Exception ex) { Console.WriteLine("Sql-Fehler InsertMessageSent()\r\n" + ex.GetType().ToString() + ": " + ex.Message + "\r\n" + ex.InnerException); throw ex; } }
/// <summary> /// 发送邮件,并且返回发送结果 /// </summary> /// <returns></returns> public SendStatus Send(out string relustMessage) { relustMessage = string.Empty; #region 验证基本信息 Regex reg = new Regex(this.RegexText, RegexOptions.IgnoreCase); if (!IsUseDefaultCredentials) // 使用账号密码登陆Smtp服务 { if (!reg.IsMatch(this.SendMailAddress)) { relustMessage = "发件地址未通过验证"; return(SendStatus.SendMailAddressIsUnmatch); } if (string.IsNullOrEmpty(this.PassWord)) { relustMessage = "发件密码为空"; return(SendStatus.PassWordIsNull); } } if (this.FromMailAddress == null || this.FromMailAddress.Length <= 0) { relustMessage = "收件地址为空"; return(SendStatus.FromMailAddressIsUnmatch); } StringBuilder FailedELst = new StringBuilder(); foreach (string item in this.FromMailAddress) { if (!reg.IsMatch(item)) { FailedELst.Append(Environment.NewLine + item); } } if (FailedELst.Length > 0) { relustMessage = "以下收件地址未通过验证:" + FailedELst; return(SendStatus.FromMailAddressIsUnmatch); } #endregion 验证基本信息 SendStatus sendStatus = SendStatus.Normal; SmtpClient smtp = new SmtpClient(); //实例化一个Smtp smtp.EnableSsl = this.IsSSL; //smtp服务器是否启用SSL加密 smtp.Host = this.SmtpAddress; //指定 Smtp 服务器地址 smtp.Port = this.SmtpPort; //指定 Smtp 服务器的端口,默认是465 ,587 if (IsUseDefaultCredentials) // SMTP服务器是否不需要身份认证 { smtp.UseDefaultCredentials = true; } else { smtp.Credentials = new NetworkCredential(this.SendMailAddress, this.PassWord); // NetworkCredential("邮箱名", "密码"); } MailMessage mm = new MailMessage(); //实例化一个邮件类 mm.Priority = MailPriority.Normal; //邮件的优先级 mm.From = new MailAddress(this.SendMailAddress, this.SendMailName, Encoding.UTF8); //收件方看到的邮件来源;第一个参数是发信人邮件地址第二参数是发信人显示的名称第三个参数是, Encoding.GetEncoding(936) 第二个参数所使用的编码,如果指定不正确,则对方收到后显示乱码,936是简体中文的codepage值 mm.ReplyTo = new MailAddress(this.SendMailAddress, this.SendMailName, Encoding.UTF8); //ReplyTo 表示对方回复邮件时默认的接收地址,即:你用一个邮箱发信,但却用另一个来收信后两个参数的意义, 同 From 的意义 StringBuilder fmLst = new StringBuilder(); foreach (string item in this.FromMailAddress) { fmLst.Append(item + ","); } mm.To.Add(fmLst.Remove(fmLst.Length - 1, 1).ToString()); //邮件的接收者,支持群发,多个地址之间用 半角逗号 分开 if (this.CarbonCopy != null && this.CarbonCopy.Length > 0 && this.IsCC) // 是否显示抄送 { StringBuilder ccLst = new StringBuilder(); foreach (string item in this.CarbonCopy) { ccLst.Append(item + ","); } mm.CC.Add(ccLst.Remove(ccLst.Length - 1, 1).ToString()); //邮件的抄送者,支持群发,多个邮件地址之间用 半角逗号 分开 } mm.Subject = this.Title; //邮件标题 mm.SubjectEncoding = CharSet; // 这里非常重要,如果你的邮件标题包含中文,这里一定要指定,否则对方收到的极有可能是乱码。// 936是简体中文的pagecode,如果是英文标题,这句可以忽略不用 mm.IsBodyHtml = this.IsBodyHtml; //邮件正文是否是HTML格式 mm.BodyEncoding = CharSet; //邮件正文的编码, 设置不正确, 接收者会收到乱码 mm.Body = this.Body; //邮件正文 if (this.Attachments != null && this.Attachments.Length > 0 && this.IsSendAttachments) { foreach (string item in this.Attachments) { mm.Attachments.Add(new Attachment(item)); //添加附件 } } try { smtp.Send(mm); relustMessage = "邮件发送成功"; sendStatus = SendStatus.Success; } catch (Exception ee) { sendStatus = SendStatus.Failed; relustMessage = ee.Message; } return(sendStatus); }
public WhenSendingASingleMessageInBlockingMode() { SenderAction = req => SendResult = req.SendFrame(Messages.SingleMessage); ReceiverAction = rep => Message = rep.ReceiveFrame(); }
/// <summary> /// Send callback /// </summary> /// <param name="socket">client socket</param> /// <param name="status">stend status</param> /// <param name="sentPacket">sent packet</param> public void OnSent(INetworkSocket socket, SendStatus status, Packet sentPacket) { ParallelPacket sentParallelPacket = ParallelPacket.FromPacket(sentPacket); if (sentParallelPacket.PacketType == ParallelPacketType.DATA) { lock (m_sendLock) { m_pendingPacketSet.Remove(sentParallelPacket); if (status == SendStatus.SUCCESS || status == SendStatus.FAIL_INVALID_PACKET) { m_pendingClientSet.Add(socket); } if (status != SendStatus.SUCCESS) { m_errorPacketSet.Add(sentParallelPacket); } if (m_pendingClientSet.Count > 0 && (m_errorPacketSet.Count > 0 || m_packetQueue.Count > 0)) m_sendReadyEvent.SetEvent(); } Task t = new Task(delegate() { OnParallelSocketSent(this, status, sentParallelPacket); }); t.Start(); } }
public WhenSendingASingleMessageWithAnAmpleTimeout() { SenderAction = req => SendResult = req.SendFrame(Messages.SingleMessage, TimeSpan.FromMilliseconds(2000)); ReceiverAction = rep => Message = rep.ReceiveFrame(TimeSpan.FromMilliseconds(2000)); }
/// <summary> /// Receive data on the TCP connection /// </summary> /// <description> /// This method has two sections based on what we want to receive (<see cref="ReceiveType"/>) /// 1. HTTP : We want to receive a HTTP response from the server /// 2. DATA : We are waiting data from the server /// </description> /// <param name="rt">Receive Type</param> public void Receive(ReceiveType rt) { _receiveDone.Reset (); // Create the state object. StateObject state = new StateObject(); state.workSocket = _tcpSocket; // Begin receiving the data from the remote device. if (rt == ReceiveType.Http) { _receiveHttpStatus = SendStatus.Ok; _tcpSocket.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (receiveCallBackHttp), state); } else if (rt == ReceiveType.Alert) { _receiveAlertStatus = SendStatus.Ok; _tcpSocket.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (receiveCallBackAlert), state); } else { _tcpSocket.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (receiveCallBackData), state); } }
/// <summary> /// 开始发送未发送成功的数据 /// </summary> /// <param name="sendItemIds">传入需要重新发送的id</param> /// <returns></returns> public bool StartSending() { // 判断是否结束 if (!SendStatus.HasFlag(SendStatus.SendFinish)) { return(false); } var allSendItems = _liteDb.Fetch <SendItem>(item => item.historyId == _currentHistoryGroupId); var sendItems = allSendItems.FindAll(item => !item.isSent); // 判断数量 if (sendItems.Count < 1) { // 发送完成的进度条 SendingProgressInfo = new SendingProgressInfo() { total = 1, index = 1, }; return(true); } else { // 更改进度 SendingProgressInfo = new SendingProgressInfo() { total = sendItems.Count, index = 0, }; } // 判断是发送还是重发 if (allSendItems.Count == sendItems.Count) { SendStatus = SendStatus.Sending; } else { SendStatus = SendStatus.Resending; } // 更改数据库中的状态 var history = _liteDb.SingleById <HistoryGroup>(_currentHistoryGroupId); if (history == null) { return(false); } history.sendStatus = SendStatus; _liteDb.Update(history); // 判断需要发送的数量 if (allSendItems.Count < 1) { history.sendStatus = SendStatus.SendFinish; _liteDb.Update(history); // 获取重发完成的信息 var sendingInfo = new SendingProgressInfo() { historyId = _currentHistoryGroupId, index = 1, total = 1, }; SendingProgressInfo = sendingInfo; return(false); } // 处理每条邮件 PreHandleSendItems(sendItems); // 开始发件 SendItems(sendItems); return(true); }
public SentItem(Guid id, SendStatus status, string statusInfo) : this(id, status) { StatusInfo = statusInfo; }
void OnCompleted(SendStatus status, string newFilename, string message) { if (_Completed != null) { Delegate d = new FileSenderCompletedEventHandler(_Completed); FileSenderCompletedEventArgs e = new FileSenderCompletedEventArgs(); e.NewFilename = newFilename; e.Status = status; e.Message = message; this._UIDispatcher.BeginInvoke(d, null, e); } }
private bool CanBeRetried(SendStatus status) { return(!CannotBeRetried(status)); }
//================================================================================ public static string Transaq_HandleData(string data) { // обработка данных, полученных коннектором от сервера Транзак string sTime = DateTime.Now.ToString("HH:mm:ss.fff"); string info = ""; // включить полученные данные в строку вывода в лог-файл string textForWindow = data; //log.WriteLog("ServerData: " + data); XmlReaderSettings xs = new XmlReaderSettings(); xs.IgnoreWhitespace = true; xs.ConformanceLevel = ConformanceLevel.Fragment; xs.DtdProcessing = DtdProcessing.Ignore; var xr = XmlReader.Create(new System.IO.StringReader(data), xs); string section = ""; string line = ""; string str = ""; string ename = ""; string evalue = ""; string attr = ""; //string values = ""; // обработка "узлов" while (xr.Read()) { switch (xr.NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: ename = xr.Name; break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.XmlDeclaration: evalue = xr.Value; break; case XmlNodeType.DocumentType: ename = xr.Name; evalue = xr.Value; break; default: break; } //................................................................................ // определяем узел верхнего уровня - "секцию" if (xr.Depth == 0) { if (xr.NodeType == XmlNodeType.Element) { section = ename; if ((section != "boards") && (section != "securities") && (section != "pits") && (section != "sec_info_upd") && (section != "quotes") && (section != "alltrades") && (section != "ticks") && (textForWindow.Length > 0) && (section != "united_portfolio")) { textForWindow = ""; //OnSendNews(data); } line = ""; str = ""; for (int i = 0; i < xr.AttributeCount; i++) { str = str + xr.GetAttribute(i) + ";"; } } if (xr.NodeType == XmlNodeType.EndElement) { //line = ""; //section = ""; } if (xr.NodeType == XmlNodeType.Text) { str = str + evalue + ";"; } } //................................................................................ // данные для рынков if (section == "markets") { //xe = (XElement)XNode.ReadFrom(xr); if (ename == "market") { if (xr.NodeType == XmlNodeType.Element) { line = ""; str = ""; for (int i = 0; i < xr.AttributeCount; i++) { str = str + xr.GetAttribute(i) + ";"; } } if (xr.NodeType == XmlNodeType.EndElement) { line = "add market: " + str; str = ""; } if (xr.NodeType == XmlNodeType.Text) { str = str + evalue + ";"; } } } //................................................................................ // данные для таймфреймов if (section == "candlekinds") { break; //if (ename == "kind") //{ // if (xr.NodeType == XmlNodeType.Element) // { // line = ""; // str = ""; // } // if (xr.NodeType == XmlNodeType.EndElement) // { // line = "add kind: " + str; // On_New_Timeframe(str); // str = ""; // } //} //else //{ // if (xr.NodeType == XmlNodeType.Text) // { // str = str + evalue + ";"; // } //} } //................................................................................ // данные для инструментов if (section == "securities") { OnSendNewSecurity(data); break; //if (ename == "security") //{ // if (xr.NodeType == XmlNodeType.Element) // { // line = ""; // str = ""; // for (int i = 0; i < xr.AttributeCount; i++) // { // str = str + xr.GetAttribute(i) + ";"; // } // } // if (xr.NodeType == XmlNodeType.EndElement) // { // line = "add security: " + str; // On_New_Security(str); // str = ""; // } //} //else //{ // if (xr.NodeType == XmlNodeType.Element) // { // for (int i = 0; i < xr.AttributeCount; i++) // { // str = str + xr.GetAttribute(i) + ";"; // } // } // if (xr.NodeType == XmlNodeType.Text) // { // str = str + evalue + ";"; // } //} } //................................................................................ // данные по свечам if (section == "candles") { OnSendNewCandles(data); break; } //................................................................................ // данные по клиенту if (section == "client") { //if (ename == "client") //{ // if (xr.NodeType == XmlNodeType.Element) // { // line = ""; // str = ""; // for (int i = 0; i < xr.AttributeCount; i++) // { // str = str + xr.GetAttribute(i) + ";"; // } // // определение параметров клиента // //string[] с_attrs = str.Split(';'); // //if (с_attrs.Length > 0) // //{ // // ClientCode = с_attrs[0]; // //} // line = "add client: " + str; // } // else // { // line = ""; // if (xr.NodeType == XmlNodeType.Text) // { // str = str + evalue + ";"; // line = "set: " + ename + "=" + evalue; // } // } //} OnSendNewClientInfo(data); break; } //................................................................................ // данные для позиций if (section == "positions") { } //................................................................................ if (section == "overnight") { if (xr.NodeType == XmlNodeType.Element) { line = ""; str = ""; for (int i = 0; i < xr.AttributeCount; i++) { str = str + "<" + xr.GetAttribute(i) + ">;"; } line = "set overnight status: " + str; } } //................................................................................ // данные о статусе соединения с сервером if (section == "server_status") { if (xr.NodeType == XmlNodeType.Element) { string attr_connected = xr.GetAttribute("connected"); if (attr_connected == "true") { _bConnected = true; } if (attr_connected == "false") { _bConnected = false; } if (attr_connected == "error") { _bConnected = false; xr.Read(); OnSendNewFormData(xr.Value); } } SendStatus?.Invoke(data); } if (section == "orders") //обрабатываем заявки { OnSendNewOrders(data); break; } if (section == "stoporders") //обрабатываем заявки { OnSendNewOrders(data); break; } if (section == "ticks") { OnSendNewTicks(data); break; } if (section == "quotes") { OnSendNewQuotes(data); break; } if (section == "alltrades") { OnSendNewAllTrades(data); break; } if (section == "trades") { OnSendNewTrades(data); break; } if (section == "united_portfolio") { OnSendNewUnitedPortfolio(data); break; } if (section == "portfolio_mct") { OnSendPortfolioMct(data); break; } if (section == "news_header" || section == "news_body") { OnSendNews(data); break; } //................................................................................ if (line.Length > 0) { //line = new string(' ',xr.Depth*2) + line; if (info.Length > 0) { info = info + (char)13 + (char)10; } info = info + line; } } //if (info.Length > 0) log.WriteLog(info); return(section); // вывод дополнительной информации для удобства отладки }
/// <summary> /// Send callback /// </summary> /// <param name="socket">client socket</param> /// <param name="status">stend status</param> /// <param name="sentPacket">sent packet</param> public void OnParallelSocketSent(IParallelSocket socket, SendStatus status, ParallelPacket sentPacket) { }
public DwhExtractSentEvent(ExtractType extractType, List <Guid> sentIds, SendStatus status, string statusInfo = "") { SentItems = sentIds.Select(x => new SentItem(x, status, statusInfo)).ToList(); ExtractType = extractType; }
/// <summary> /// Send callback /// </summary> /// <param name="client">client</param> /// <param name="status">send status</param> /// <param name="sentPacket">sent packet</param> public void OnSent(IParallelClient client, SendStatus status, ParallelPacket sentPacket) { }
public static SendStatusResult SendStatusResult(string messageId = null, SendStatus status = default) { return(new SendStatusResult(messageId, status)); }
public SendResult(SendStatus sendStatus, string errorMessage) { SendStatus = sendStatus; ErrorMessage = errorMessage; }
public SentItem(Guid id, SendStatus status, string statusInfo, ExtractType extractType) : this(id, status) { ExtractType = extractType; StatusInfo = statusInfo; }
/// <summary> /// Callback method to receive DATA /// </summary> /// <param name="ar">Async Result</param> private void receiveCallBackData( IAsyncResult ar ) { try { _receiveDataStatus = SendStatus.Ok; StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // Stock number of bytes received so far (to show on screen) _bytesReceived += bytesRead; //Console.WriteLine("---------- NEW MESSAGE ----------------------------------------------------"); //Console.WriteLine("---------- Received bytes.........: {0}", bytesRead.ToString()); // Write bytes read to main data buffer byte[] tmpdata = new byte[bytesRead]; Array.Copy(state.buffer, tmpdata, bytesRead); _connectionBuffer.Write(tmpdata); //Console.WriteLine("---------- END MESSAGE ----------------------------------------------------"); // Continue getting data client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(receiveCallBackData), state); } } catch { _receiveDataStatus = SendStatus.Error; _receiveDataStatusMessage = "An error occured receiving scanner data."; } finally { _receiveDone.Set(); } }
/// <summary> /// 发送结果 /// </summary> /// <param name="sendStatus"></param> /// <param name="messageStoreResult"></param> /// <param name="errorMessage"></param> public SendResult(SendStatus sendStatus, MessageStoreResult messageStoreResult, string errorMessage) { SendStatus = sendStatus; MessageStoreResult = messageStoreResult; ErrorMessage = errorMessage; }
/// <summary> /// Send callback /// </summary> /// <param name="ar">Async Result</param> private void sendCallback(IAsyncResult ar) { try { Socket client = (Socket) ar.AsyncState; client.EndSend(ar); _sendStatus = SendStatus.Ok; _sendStatusMessage = "Sent."; } catch { _sendStatus = SendStatus.Error; _sendStatusMessage = "An error occured while sending data."; } finally { _sendDone.Set (); } }
public SentItem(Guid id, SendStatus status, string statusInfo, string extract = "") : this(id, status) { Extract = extract; StatusInfo = statusInfo; }
/// <summary> /// 送信処理 /// </summary> protected void sendTask() { switch (sendStatus) { case SendStatus.Ready : /* 送信予約待ち */ // 送信データありの場合 if (sendQueue.Count > 0) { // コマンドを取り出す sendCommand = ((CommandStruct)sendQueue.Peek()).Clone(); isPolling = false; } // ポーリングタイムアウト発生 else if (isPolling) { sendCommand = new CommandStruct(); sendCommand.Cmd = 'R'; sendCommand.Address = 0x000A; sendCommand.size = 1; } // それ以外 else { return; } // リトライ回数を初期化 sendRetryCount = 0; sendStatus = SendStatus.Sending; break; case SendStatus.Sending : /* 送信中 */ // コマンドをバイト列に変換する byte[] cmd = sendCommand.Encode(); // コマンドを送信する。 try { write(cmd, 0, cmd.Length); sendTimer.Restart(); sendStatus = SendStatus.AckWaiting; } catch { ts.TraceInformation("Write処理失敗"); execSendRetry(); return; } break; case SendStatus.AckWaiting : /* Ack待ち */ // タイムアウト発生の場合はリトライ処理を行う。 if (sendTimer.ElapsedMilliseconds > timeout) { ts.TraceInformation("Ack待ちタイムアウトが発生"); execSendRetry(); return; } break; case SendStatus.CommandProcessing : /* コマンド実行 */ // 不正Ackの場合は、リトライを行う。 if (CommandUtil.CheckAckCommand(sendCommand, sendAckCommand) == false) { ts.TraceInformation("不正Ack受信"); execSendRetry(); return; } // Online状態でなければ、Onlineに切り替え if (status != Status.Online) { // 切断理由をリセットする comError = SystemConstants.COM_ERROR_NORMAL; // StatusをOnlineにする。 status = Status.Online; // 接続イベント発生 if (connstatusChange != null) { ConnStatusEventArgs e = new ConnStatusEventArgs(); e.EventCode = SystemConstants.EVENT_CONNECT; ctl.Invoke(connstatusChange, new object[] { this, e }); } } // コマンド実行 execCommand(sendAckCommand, sendCommand); // ポーリング通信の場合 if (isPolling) { // ポーリング状態の解除 isPolling = false; } // キューからのデータ指示の場合 else { // キューから1件データを削除する sendQueue.Dequeue(); } sendStatus = SendStatus.Ready; break; } }
private void receiveCallBackAlert( IAsyncResult ar ) { try { StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { _alertResponse = bytesTostring(state.buffer); } } catch { _receiveAlertStatus = SendStatus.Error; _receiveAlertStatusMessage = "An error occured receiving alert response."; } finally { _receiveAlertStatusMessage = _alertResponse; _receiveDone.Set(); } }
/// <summary> /// 更新批次详情表发送状态 /// </summary> /// <param name="batchId"></param> /// <param name="channelId"></param> /// <param name="statusModel"></param> /// <returns></returns> public static int UpdateDetailSendingStatus(string batchId, int channelId, SendStatus statusModel) { MessageSysDAL dal = new MessageSysDAL(); return(dal.UpdateDetailSendingStatus(batchId, channelId, statusModel)); }
/// <summary> /// Callback method to receive a HTTP response /// </summary> /// <param name="ar">Async Result</param> private void receiveCallBackHttp( IAsyncResult ar ) { try { StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { byte[] tmpdata = new byte[15]; Array.Copy(state.buffer, tmpdata, 15); _httpResponse = bytesTostring(tmpdata); } } catch { _receiveHttpStatus = SendStatus.Error; _receiveHttpStatusMessage = "An error occured receiving http response."; } finally { _receiveDone.Set(); } }
public void SetStatus(ulong deliveryTag, SendStatus status) { SetStatus(deliveryTag, status, ""); }
public void SetStatus(ulong deliveryTag, SendStatus status, string description) { var messageState = _statesByDeliveryTag[deliveryTag]; SetSendStatus(messageState, status, description); }
public void SetStatus(string messageId, SendStatus status) { SetStatus(messageId, status, ""); }
public SentItem(Guid id, SendStatus status) { Id = id; Status = status; }
public void SetStatus(string messageId, SendStatus status, string description) { var messageState = _statesByMessageId[messageId]; SetSendStatus(messageState, status, description); }
public CTExtractSentEvent(List <Guid> sentIds, SendStatus status, ExtractType extractType, string statusInfo = "") { SentItems = sentIds.Select(x => new SentItem(x, status, statusInfo, extractType)).ToList(); }
/// <summary> /// 送信リトライ処理 /// </summary> protected void execSendRetry() { // リトライ回数内 if (sendRetryCount < SystemConstants.MAX_RETRY_COUNT) { status = Status.Suspended; sendStatus = SendStatus.Sending; ts.TraceInformation("リトライ{0}回目", new object[] { sendRetryCount + 1 }); sendRetryCount++; } // リトライ回数オーバー else { // 通信途絶 PortClose(); ts.TraceInformation("リトライ回数をオーバーしました。"); // 切断理由を変更 comError = SystemConstants.COM_ERROR_RETRYERROR; // 切断イベントの通知 if (connstatusChange != null) { ConnStatusEventArgs args = new ConnStatusEventArgs(); args.EventCode = SystemConstants.EVENT_DISCONNECT; ctl.Invoke(connstatusChange, new object[] {this, args}); ts.TraceInformation("切断イベントが発生しました。"); } } }