/// <summary> /// Handler for the IChannel.IncomingMessage event /// </summary> /// <param name="msg">The message received</param> /// <param name="channel">The channel that received the message</param> public void OnChannelIncomingMessage(OPSTelegrama msg, IChannel channel) { if (ValidateMessage(msg)) { string ip; int port; TcpIpUri.UriAsAddressPort(channel.Uri, out ip, out port); IPacketizer packetizer = msg.Packetizer; FecsBecsHeader hd = new FecsBecsHeader(channel.Uri, ip, packetizer.PacketInfo); for (int i = 0; i < packetizer.PacketsCount; i++) { _outQueue.Send(hd, packetizer[i]); FecsMain.Logger.AddLog( string.Format("[OutputQueueFecsAdapter]:Message received from {0} [{1}]", channel.Uri, msg.XmlData), LoggerSeverities.Info); } } else { FecsMain.Logger.AddLog( string.Format("[OutputQueueFecsAdapter]:Message not validated from {0} [{1}]", channel.Uri, msg.XmlData), LoggerSeverities.Error); NackMessage(msg, channel); } }
/// <summary> /// Checks the correctness of an incoming message /// </summary> /// <param name="packet">The datagram to validate</param> /// <returns>true if the message is correct, false otherwise</returns> public bool Validate(OPSTelegrama packet) { // First of all, let's load the XML and let's check if it is well-formed System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { doc.LoadXml(packet.XmlData); } catch { return(false); } // For each of the messages in the packet... foreach (XmlNode item in doc.DocumentElement.ChildNodes) { // Second, is there any Schema that can apply to the document? if (!_xmlSchemas.ContainsKey(item.Name)) { FecsMain.Logger.AddLog("[FecsMessageValidator::Validate]:There is no Schema", LoggerSeverities.Debug); return(false); } // Third, let's validate against schema if (!((XmlSchemaCache)_xmlSchemas[item.Name]).ValidateXmlDocument(item)) { FecsMain.Logger.AddLog("[FecsMessageValidator::Validate]:There is no Schema", LoggerSeverities.Debug); return(false); } } return(true); }
internal NotificationArgs(RequestOutcome outcome, OPSTelegrama response) { if (response != null) { _response = OPSTelegramaFactory.CreateOPSTelegrama(response.FullData); } _outcome = outcome; }
/// <summary> /// Handler for the channel IncomingMessage event /// </summary> /// <param name="msg">The received message</param> /// <param name="channel">The channel that received the message</param> private void OnChannelIncomingMessage(OPSTelegrama msg, IChannel channel) { if (_waiting) { // ThreadPool.QueueUserWorkItem(new WaitCallback(NotifyThreadProc), // new NotificationArgs(RequestOutcome.SendOK, msg)); DoNotify(new NotificationArgs(RequestOutcome.SendOK, msg)); } }
/// <summary> /// Sends a NACK for the received message /// </summary> /// <param name="channel">The channel that received the message</param> private void NackMessage(IChannel channel) { string nackBody = "<ne id=\"0\"/>"; OPSTelegrama t = OPSTelegramaFactory.CreateOPSTelegrama(Correlation.NextId, nackBody); channel.SendMessage(t); FecsMain.Logger.AddLog( string.Format("Message sent to {0} [{1}]", channel.Uri, nackBody), LoggerSeverities.Debug); }
public void ReceiveMessage(OPSTelegrama msg) { if (IncomingMessage != null) { IncomingMessage(msg, this); } else { BecsMain.Logger.AddLog("Error: IncomingMessage event handler is null in BecsChannel.ReceiveMessage.", OPS.Comm.LoggerSeverities.Error); } }
private void OnRequestMessageResponse(decimal msgId, RequestOutcome outcome, OPSTelegrama response) { if (MessageArrived != null) { MessageArrived(msgId, outcome, response.XmlData, this, response.Packetizer.PacketInfo.SourceId); } else { CommMain.Logger.AddLog("WARNING: MessageProcessor.OnRequestMessageResponse: MessageArrived is null.", LoggerSeverities.Debug); } }
//<< LDR 2004.07.16 #endregion // Public API #region Private methods /// <summary> /// Checks the correctness of an incoming message /// </summary> /// <param name="msg">The message to validate</param> /// <returns>true if the message is correct, false otherwise</returns> private bool ValidateMessage(OPSTelegrama msg) { bool retVal = msg.Correct; if (retVal) { if (_validator != null) { retVal = _validator.Validate(msg); } } return(retVal); }
/// <summary> /// Builds a packet containing only the messages that need to be /// retried. The status of the messages is set to Sending /// </summary> /// <param name="msg">The object that receives the packet</param> /// <param name="msgIds">The identifiers of the messages in the packet. Only keys /// are important</param> /// <returns>The number of messages packed</returns> private int PrepareMessagesToSend(out OPSTelegrama msg, out Hashtable msgIds) { msg = null; StringBuilder packet = null; int msgCount = GetMessagesPacket(out packet, out msgIds); Debug.WriteLine("Request - Messages in packet: " + msgCount); if (msgCount > 0 && packet != null) { msg = OPSTelegramaFactory.CreateOPSTelegrama(Correlation.NextId, packet.ToString()); } return(msgCount); }
/// <summary> /// Sends a message and waits for the currently defined timeout /// </summary> /// <param name="msgsIds">A table containing the identifiers of the /// messages packed in msg. Only keys matter. Keys are of type /// System.Decimal</param> /// <param name="msg">The message to be sent</param> public void SendMessage(Hashtable msgsIds, OPSTelegrama msg) { _messageCount = msgsIds.Count; _msgsIds = msgsIds; _waiting = true; try { _channel.SendMessage(msg); } catch (Exception) { DoNotify(new NotificationArgs(RequestOutcome.SendError, null)); } }
/// <summary> /// Sends a message immediately and without expecting a response /// </summary> /// <param name="msg">The message to send</param> public void OneWaySend(string msg) { OPSTelegrama packet = OPSTelegramaFactory.CreateOPSTelegrama(Correlation.NextId, msg); try { _channel.SendMessage(packet); } catch (Exception ex) { //Debug.WriteLine("MsgProc OneWaySend error: " + ex.Message); CommMain.Logger.AddLog(ex); } }
/// <summary> /// Updates the address cache with the unit of a packet source /// </summary> /// <param name="packet">A received packet</param> /// <param name="uri">The uri of the channel through which the packet came</param> private void UpdateAddressCache(OPSTelegrama packet, string uri) { string ip; int port; TcpIpUri.UriAsAddressPort(uri, out ip, out port); OPSPacketizer packetizer = new OPSPacketizer(packet.XmlData); PacketData packData = packetizer.PacketInfo; if (packData != null) { string src = packData.SourceId; if ((src != null) && (src != "")) { Configuration.AddressCache.GetAddressCache().CacheUnitAddress( decimal.Parse(src), ip); } } }
/// <summary> /// Handler for the ChannelAdapter MessageResponse event /// </summary> /// <param name="outcome">The outcome of the message</param> /// <param name="response">The response received when the /// outcome indicates success, null otherwise</param> private void OnChannelAdapterMessageResponse(RequestOutcome outcome, OPSTelegrama response) { if (_sending && response != null && _responseHandler != null) { ThreadPool.QueueUserWorkItem( new WaitCallback(HandleResponseThreadProc), new RequestResponse(outcome, response)); } else { if (outcome == RequestOutcome.ReceiveError || outcome == RequestOutcome.SendError) { Debug.WriteLine("Request - Finalizing request due to receive or send error"); FinalizeRequest(); } } }
/// <summary> /// Sends the notification that the message has been sent /// </summary> /// <param name="msg">The message just sent</param> private void NotifySend(OPSTelegrama msg) { try { if (_outcomingMsgHandler != null) { _outcomingMsgHandler(msg, this); } else { CommMain.Logger.AddLog("WARNING: SocketChannel.NotifySend: _outcomingMsgHandler is null for [" + msg.XmlData + "].", LoggerSeverities.Error); } } catch (Exception ex) { //Debug.WriteLine("SocketChannel - Exception NotifySend: " + ex.Message); CommMain.Logger.AddLog(ex); } }
/// <summary> /// Sends a NACK for the received message /// </summary> /// <param name="msg">The message to not acknowledge</param> /// <param name="channel">The channel that received the message</param> private void NackMessage(OPSTelegrama msg, IChannel channel) { string[] msgsId = null; if (msg != null) { msgsId = msg.GetMessagesId(); } if (msgsId != null) { for (int i = 0; i < msgsId.Length; i++) { string nackBody = string.Format("<ne id=\"{0}\"/>", msgsId[i]); OPSTelegrama t = OPSTelegramaFactory.CreateOPSTelegrama(Correlation.NextId, nackBody); channel.SendMessage(t); FecsMain.Logger.AddLog( string.Format("Message sent to {0} [{1}]", channel.Uri, msg.XmlData), LoggerSeverities.Debug); } } }
//<< LDR 2004.07.16 /// <summary> /// Sends a message to the remote end point /// </summary> /// <param name="msg">The message to send</param> public void SendMessage(OPSTelegrama msg) { Monitor.Enter(_outQueue); try { _outQueue.Enqueue(msg); _sendEvent.Set(); NotifySend(msg); } catch (Exception ex) { //Debug.WriteLine(ex.Message); CommMain.Logger.AddLog(ex); throw; } finally { Monitor.Exit(_outQueue); } }
private void OnChannelIncomingMessage(OPSTelegrama packet, IChannel channel) { if (MessageArrived != null) { if (packet != null) { XmlDocument doc = new XmlDocument(); doc.LoadXml(packet.XmlData); XmlNode root = doc; if (root.ChildNodes.Count > 0) { /// Is a packet containing messages UpdateAddressCache(packet, channel.Uri); IPacketizer pt = packet.Packetizer; for (int i = 0; i < pt.PacketsCount; i++) { string msg = pt[i]; Debug.WriteLine("MsgProc - Arrived: " + msg); MessageAccess acc = new MessageAccess(msg); string msgId = acc.GetMessageId(); MessageArrived(Convert.ToDecimal(msgId), RequestOutcome.SendOK, msg, this, packet.Packetizer.PacketInfo.SourceId); } } else { /// Is an ACK eventually containing response data MessageAccess acc = new MessageAccess(packet.XmlData); string msgId = acc.GetMessageId(); MessageArrived(Convert.ToDecimal(msgId), RequestOutcome.SendOK, packet.XmlData, this, packet.Packetizer.PacketInfo.SourceId); } } } else { CommMain.Logger.AddLog("WARNING: MessageProcessor.OnChannelIncomingMessage: MessageArrived is null.", LoggerSeverities.Debug); } }
/// <summary> /// Handler for the inbound message queue ReceiveCompleted event /// </summary> /// <param name="header">The header of the incoming message</param> /// <param name="body">The body of the incoming message</param> public void OnQueueReceiveCompleted(BecsFecsHeader header, string body) { /// JLB 2004.07.21 - time sending a message /// Org.Mentalis.Utilities.StopWatch sw = new Org.Mentalis.Utilities.StopWatch(); IChannel channel = _channelMgr.GetChannel(header.Fid); long d = sw.Peek(); if (channel == null) { try { //>> LDRTEST0 //channel = _channelMgr.OpenChannel(header.Fid, ChannelType.FecsQueue); //<< LDRTEST0 } catch (Exception ex) { FecsMain.Logger.AddLog( string.Format("Couldn't open channel to send to {0}.", header.Fid), LoggerSeverities.Error); FecsMain.Logger.AddLog(ex); } if (channel != null) { SetupChannel(channel); } } if (channel != null) { if (d > 100) { FecsMain.Logger.AddLog(string.Format("Delay for GetChannel({1}) {0} ms", d, channel.Uri), LoggerSeverities.Debug); } try { OPSTelegrama t = OPSTelegramaFactory.CreateOPSTelegrama(Correlation.NextId, body); channel.SendMessage(t); FecsMain.Logger.AddLog( string.Format("Message sent to {0} [{1}].", channel.Uri, t.XmlData), LoggerSeverities.Info); } catch (Exception ex) { _channelMgr.CloseChannel(header.Fid); FecsMain.Logger.AddLog( string.Format("Couldn't send to {0}. Closing channel.", header.Fid), LoggerSeverities.Error); FecsMain.Logger.AddLog(ex); } } else { FecsMain.Logger.AddLog(string.Format("Delay for GetChannel({1}) {0} ms", d, header.Fid), LoggerSeverities.Debug); FecsMain.Logger.AddLog( string.Format("Message NOT sent to {0} [{1}].", header.Fid, body), LoggerSeverities.Error); } }
/// <summary> /// Handler for the channel OutcomingMessage event /// </summary> /// <param name="msg">The message sent</param> /// <param name="channel">The channel through wich the message was sent</param> private void OnChannelOutcomingMessage(OPSTelegrama msg, IChannel channel) { Debug.WriteLine("RequestAdapter - OnChannelOutcomingMessage:\n" + msg.XmlData); }
public void SendMessage(OPSTelegrama msg) { _outAdapter.SendMessage(msg, _uri); }
public void SendMessage(OPSTelegrama msg) { _outgoingChannel.SendMessage(msg); }
/// <summary> /// The thread responsible for sending messages /// </summary> /// <param name="state">Is a SocketChannel object</param> private void ThreadSendProc(object state) { bool send = true; Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; while (send && !_closing) { Debug.WriteLine("SocketChannel - Blocking to send data"); try { _sendEvent.WaitOne(); } catch (Exception ex) { //Debug.WriteLine("SocketChannel.ThreadSendProc - Exception: " + ex.Message); CommMain.Logger.AddLog(ex); } Debug.WriteLine("SocketChannel - Unblocked to send data"); if (_closing) { NotifySendError(SocketErrors.SendingError); break; } Monitor.Enter(_outQueue); try { while (_outQueue.Count > 0) { OPSTelegrama t = (OPSTelegrama)_outQueue.Dequeue(); byte[] data = t.FullData; //Debug.WriteLine("SocketChannel - About to send, length=" + data.Length.ToString()); //CommMain.Logger.AddLog("SocketChannel - About to send, length=" + data.Length.ToString(), // LogLevels.DEBUG); _socket.Send(data, 0, data.Length, SocketFlags.None); Thread.Sleep(0); } } catch (SocketException sockEx) { //Debug.WriteLine(sockEx.Message); CommMain.Logger.AddLog(sockEx); if (sockEx.ErrorCode == WSAECONNRESET) { // The remote end-point closed the connection NotifySendError(SocketErrors.RemoteClosed); send = false; } } catch (Exception ex) { //Debug.WriteLine(ex.Message); CommMain.Logger.AddLog(ex); NotifySendError(SocketErrors.SendingError); send = false; } finally { _outQueue.Clear(); Monitor.Exit(_outQueue); } } Debug.WriteLine("SocketChannel - ThreadSendProc ending"); }
/// <summary> /// Sends a packet to the queue /// </summary> /// <param name="packet">The packet to send</param> /// <param name="fromUri">The originating channel URI</param> public void SendMessage(OPSTelegrama packet, string fromUri) { BecsFecsHeader hd = new BecsFecsHeader("0", "0", fromUri, 0, 1, true); _outQueue.Send(hd, packet.XmlData); }
/// <summary> /// The thread procedure in charge of sending messages following the /// retry policy /// </summary> /// <param name="state">Unused</param> private void MainSenderThreadProc(object state) { _cancelling = false; bool requestDone = false; // Total retries loop while (_messagesLeft > 0 && _totalRetriesPending > 0 && !_cancelling && !requestDone) { _timedOut = false; _partialRetriesPending = _partialRetries; // Partial retries loop while (_messagesLeft > 0 && _partialRetriesPending > 0 && !_cancelling && !requestDone) { OPSTelegrama packet = null; Hashtable msgIds = null; _messagesLeft = PrepareMessagesToSend(out packet, out msgIds); if (_messagesLeft > 0) { _sending = true; Debug.WriteLine("Request - About to retry"); UpdateMessageRetries(); try { _channelAdapter.SendMessage(msgIds, packet); WaitForCompletion(); if (_timedOut) { Debug.WriteLine("Request - Partial timeout"); _sending = false; _timedOut = false; } else { requestDone = true; } } catch (Exception ex) { //Debug.WriteLine("Request.MainSenderThreadProc - SendMessage failed: " + ex.Message); CommMain.Logger.AddLog(ex); UpdateMessageStatus(msgIds, MessageStatus.SendFailed); } } _partialRetriesPending--; } if (_messagesLeft > 0) { WaitForCompletion(_totalTimeout); if (_timedOut) { Debug.WriteLine("Request - Total timeout"); _timedOut = false; } } _totalRetriesPending--; } FinalizeRequest(); }
internal RequestResponse(RequestOutcome outcome, OPSTelegrama msg) { _outcome = outcome; _msg = msg; }
private void OnInQueueReceiveCompleted(FecsBecsHeader header, string body) { if (_channelMgr != null) { string uri = header.ID; IChannel channel = _channelMgr.GetChannel(uri); if (channel == null) { channel = _channelMgr.OpenChannel(uri, ChannelType.BecsQueue); if (channel != null) { MessageProcessorManager.OnNewConnection(channel); } } if (channel != null) { BecsChannel bc = (BecsChannel)channel; StringBuilder packet = new StringBuilder(256); packet.AppendFormat(null, "<{0} {1}=\"{2}\" {3}=\"{4}\">{5}</{0}>", Tags.Packet, Tags.PacketSrcAttr, header.PacketInfo.SourceId, Tags.PacketDateAttr, Dtx.DtxToString(header.PacketInfo.Dtx), body); string xml = packet.ToString(); ILogger localLogger = null; try { Database d = null; CmpUnitsDB cmpUnits = new CmpUnitsDB(); //d = DatabaseFactory.GetDatabase(); localLogger = DatabaseFactory.Logger; if (localLogger != null) { localLogger.AddLog("[OnInQueueReceiveCompleted]: Updating ID: " + header.PacketInfo.SourceId + " IP :" + header.IP, LoggerSeverities.Debug); } if (Convert.ToInt32(header.PacketInfo.SourceId) != -1) { if (cmpUnits.UpdateIP(Convert.ToInt32(header.PacketInfo.SourceId), header.IP) != 1) { if (localLogger != null) { localLogger.AddLog("[OnInQueueReceiveCompleted]: Error Updating IP", LoggerSeverities.Debug); } } else { if (localLogger != null) { localLogger.AddLog("[OnInQueueReceiveCompleted]: Update OK", LoggerSeverities.Debug); } } } } catch { // Do not do nothing?? // Si tenemos un error en realizar un update de la ip // no hacemos nada if (localLogger != null) { localLogger.AddLog("[OnInQueueReceiveCompleted]: Error Updating IP", LoggerSeverities.Debug); } } Interlocked.Increment(ref _packetId); OPSTelegrama opsTel = OPSTelegramaFactory.CreateOPSTelegrama(_packetId, xml); bc.ReceiveMessage(opsTel); } } }