Esempio n. 1
0
File: Bus.cs Progetto: Bourl/Zebus
        private void SendMessageProcessingFailedIfNeeded(MessageDispatch dispatch, DispatchResult dispatchResult, TransportMessage failingTransportMessage = null)
        {
            if (dispatchResult.Errors.Count == 0 || dispatchResult.Errors.All(error => error is DomainException))
            {
                return;
            }

            if (failingTransportMessage == null)
            {
                failingTransportMessage = ToTransportMessage(dispatch.Message, MessageId.NextId());
            }

            string jsonMessage;

            try
            {
                jsonMessage = JsonConvert.SerializeObject(dispatch.Message);
            }
            catch (Exception ex)
            {
                jsonMessage = string.Format("Unable to serialize message :{0}{1}", System.Environment.NewLine, ex);
            }
            var errorMessages           = dispatchResult.Errors.Select(error => error.ToString());
            var errorMessage            = string.Join(System.Environment.NewLine + System.Environment.NewLine, errorMessages);
            var messageProcessingFailed = new MessageProcessingFailed(failingTransportMessage, jsonMessage, errorMessage, SystemDateTime.UtcNow, dispatchResult.ErrorHandlerTypes.Select(x => x.FullName).ToArray());
            var peers = _directory.GetPeersHandlingMessage(messageProcessingFailed);

            SendTransportMessage(ToTransportMessage(messageProcessingFailed, MessageId.NextId()), peers);
        }
Esempio n. 2
0
        protected void DoIndividualAcknowledge(Message message)
        {
            MessageDispatch dispatch = null;

            lock (this.dispatchedMessages)
            {
                foreach (MessageDispatch originalDispatch in this.dispatchedMessages)
                {
                    if (originalDispatch.Message.MessageId.Equals(message.MessageId))
                    {
                        dispatch = originalDispatch;
                        this.dispatchedMessages.Remove(originalDispatch);
                        break;
                    }
                }
            }

            if (dispatch == null)
            {
                Tracer.DebugFormat("Attempt to Ack MessageId[{0}] failed because the original dispatch is not in the Dispatch List", message.MessageId);
                return;
            }

            MessageAck ack = new MessageAck();

            ack.AckType       = (byte)AckType.IndividualAck;
            ack.ConsumerId    = this.info.ConsumerId;
            ack.Destination   = dispatch.Destination;
            ack.LastMessageId = dispatch.Message.MessageId;
            ack.MessageCount  = 1;

            Tracer.Debug("Sending Individual Ack for MessageId: " + ack.LastMessageId.ToString());
            this.session.SendAck(ack);
        }
Esempio n. 3
0
        protected void DispatchMessage(MessageDispatch dispatch)
        {
            bool dispatched = false;

            // Override the Message's Destination with the one from the Dispatch since in the
            // case of a virtual Topic the correct destination ack is the one from the Dispatch.
            // This is a bit of a hack since we should really be sending the entire dispatch to
            // the Consumer.
            dispatch.Message.Destination = dispatch.Destination;

            lock (sessions.SyncRoot)
            {
                foreach (Session session in sessions)
                {
                    if (session.DispatchMessage(dispatch.ConsumerId, dispatch.Message))
                    {
                        dispatched = true;
                        break;
                    }
                }
            }

            if (!dispatched)
            {
                Tracer.Error("No such consumer active: " + dispatch.ConsumerId);
            }
        }
        public bool Iterate()
        {
            if (this.listener != null)
            {
                MessageDispatch dispatch = this.unconsumedMessages.DequeueNoWait();
                if (dispatch != null)
                {
                    try
                    {
                        Message message = CreateStompMessage(dispatch);
                        BeforeMessageIsConsumed(dispatch);
                        listener(message);
                        AfterMessageIsConsumed(dispatch, false);
                    }
                    catch (NMSException e)
                    {
                        this.session.Connection.OnSessionException(this.session, e);
                    }

                    return(true);
                }
            }

            return(false);
        }
Esempio n. 5
0
        public static async Task DeliveryPostage(
            [QueueTrigger(QueueNames.CommSendPostage)] MessageDispatch sendMessage,
            [Table(TableNames.CommSchedule, CommSchedulePartitionKeys.InProgress, "{RowKey}")] TableEntityAdapter <MessageSchedule> schedule,
            [Table(TableNames.CommMessage, CommMessagePartitionKeys.Created, "{MessageReference}")] TableEntityAdapter <Message> message,
            [Table(TableNames.CommSchedule)] CloudTable scheduleTable,
            [Inject] App app,
            [Inject] IScheduleIdGenerator idGenerator,
            ILogger log)
        {
            if (schedule == null)
            {
                return;
            }

            var postage = message.GetMessageOf <Postage>();

            // handle unexpected non existing message
            if (postage == null)
            {
                await schedule.MoveTo(scheduleTable, s => CommSchedulePartitionKeys.Skipped).ConfigureAwait(false);

                return;
            }

            await schedule.MarkScheduleSent(scheduleTable, app, idGenerator);
        }
Esempio n. 6
0
        private Message CreateStompMessage(MessageDispatch dispatch)
        {
            var message = dispatch.Message.Clone() as Message;

            if (message == null)
            {
                throw new Exception($"Message was null => {dispatch.Message}");
            }

            message.Connection = _session.Connection;

            if (_session.IsClientAcknowledge)
            {
                message.Acknowledger += DoClientAcknowledge;
            }
            else if (_session.IsIndividualAcknowledge)
            {
                message.Acknowledger += DoIndividualAcknowledge;
            }
            else
            {
                message.Acknowledger += DoNothingAcknowledge;
            }

            return(message);
        }
Esempio n. 7
0
        protected void DispatchMessage(MessageDispatch dispatch)
        {
            lock (dispatchers.SyncRoot)
            {
                if (dispatchers.Contains(dispatch.ConsumerId))
                {
                    IDispatcher dispatcher = (IDispatcher)dispatchers[dispatch.ConsumerId];

                    // Can be null when a consumer has sent a MessagePull and there was
                    // no available message at the broker to dispatch.
                    if (dispatch.Message != null)
                    {
                        dispatch.Message.ReadOnlyBody       = true;
                        dispatch.Message.ReadOnlyProperties = true;
                        dispatch.Message.RedeliveryCounter  = dispatch.RedeliveryCounter;
                    }

                    dispatcher.Dispatch(dispatch);

                    return;
                }
            }

            Tracer.Error("No such consumer active: " + dispatch.ConsumerId);
        }
Esempio n. 8
0
        public void TestDequeueNoWait()
        {
            MessageDispatchChannel channel = new MessageDispatchChannel();

            MessageDispatch dispatch1 = new MessageDispatch();
            MessageDispatch dispatch2 = new MessageDispatch();
            MessageDispatch dispatch3 = new MessageDispatch();

            Assert.IsTrue(channel.Running == false);
            Assert.IsTrue(channel.DequeueNoWait() == null);

            channel.Enqueue(dispatch1);
            channel.Enqueue(dispatch2);
            channel.Enqueue(dispatch3);

            Assert.IsTrue(channel.DequeueNoWait() == null);
            channel.Start();
            Assert.IsTrue(channel.Running == true);

            Assert.IsTrue(channel.Empty == false);
            Assert.IsTrue(channel.Count == 3);
            Assert.IsTrue(channel.DequeueNoWait() == dispatch1);
            Assert.IsTrue(channel.DequeueNoWait() == dispatch2);
            Assert.IsTrue(channel.DequeueNoWait() == dispatch3);

            Assert.IsTrue(channel.Count == 0);
            Assert.IsTrue(channel.Empty == true);
        }
Esempio n. 9
0
        /// <summary>
        /// Called on a background thread to raise an event indicating that a message has been picked up.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessAndDispatchMessageQueueItem(MessageDispatch message)
        {
            if (message.Port30003MessageEventArgs != null)
            {
                OnPort30003MessageReceived(message.Port30003MessageEventArgs);
            }
            else if (message.RawBytesEventArgs != null)
            {
                OnRawBytesReceived(message.RawBytesEventArgs);
            }
            else if (message.ModeSBytesEventArgs != null)
            {
                OnModeSBytesReceived(message.ModeSBytesEventArgs);
            }
            else
            {
                var modeSMessageArgs = message.ModeSMessageEventArgs;
                OnModeSMessageReceived(modeSMessageArgs);

                BaseStationMessage cookedMessage;
                lock (_SyncLock) {
                    cookedMessage = RawMessageTranslator == null ? null : RawMessageTranslator.Translate(modeSMessageArgs.ReceivedUtc, modeSMessageArgs.ModeSMessage, modeSMessageArgs.AdsbMessage);
                }
                if (cookedMessage != null)
                {
                    OnPort30003MessageReceived(new BaseStationMessageEventArgs(cookedMessage));
                }
            }
        }
Esempio n. 10
0
        private MessageDispatch Extractdispatch(DbDataReader dbDataReader)
        {
            MessageDispatch dispatch = new MessageDispatch();

            Populatedispatch(dispatch, dbDataReader);
            return(dispatch);
        }
Esempio n. 11
0
 private void Populatedispatch(MessageDispatch dispatch, DbDataReader dbDataReader)
 {
     if (dbDataReader[MessageDispatchColumn.ID] != null &&
         long.TryParse(dbDataReader[MessageDispatchColumn.ID].ToString(), out long id))
     {
         dispatch.Id = id;
     }
     if (dbDataReader[MessageDispatchColumn.EMAIL_ADDRESS] != null)
     {
         dispatch.EmailAddress = dbDataReader[MessageDispatchColumn.EMAIL_ADDRESS]
                                 .ToString();
     }
     if (dbDataReader[MessageDispatchColumn.MESSAGE_ID] != null &&
         long.TryParse(dbDataReader[MessageDispatchColumn.MESSAGE_ID].ToString(), out long messageid))
     {
         dispatch.MessageId = messageid;
     }
     if (dbDataReader[MessageDispatchColumn.MESSAGE_RECEIVED] != null &&
         bool.TryParse(dbDataReader[MessageDispatchColumn.MESSAGE_RECEIVED].ToString(), out bool messageReceived))
     {
         dispatch.MessageReceived = messageReceived;
     }
     //var hh = dbDataReader[MessageDispatchColumn.MESSAGE_RECEIVED_TIME];
     if (dbDataReader[MessageDispatchColumn.MESSAGE_RECEIVED_TIME] != null &&
         DateTime.TryParse(dbDataReader[MessageDispatchColumn.MESSAGE_RECEIVED_TIME].ToString(), out DateTime receivedTime))
     {
         dispatch.MessageReceivedTime = receivedTime;
     }
 }
        public MessageDispatch Dequeue(TimeSpan timeout)
        {
            MessageDispatch result = null;

            this.mutex.WaitOne();

            // Wait until the channel is ready to deliver messages.
            if (timeout != TimeSpan.Zero && !Closed && (Empty || !Running))
            {
                // This isn't the greatest way to do this but to work on the
                // .NETCF its the only solution I could find so far.  This
                // code will only really work for one Thread using the event
                // channel to wait as all waiters are going to drop out of
                // here regardless of the fact that only one message could
                // be on the Queue.
                this.waiter.Reset();
                this.mutex.ReleaseMutex();
                this.waiter.WaitOne((int)timeout.TotalMilliseconds, false);
                this.mutex.WaitOne();
            }

            if (!Closed && Running && !Empty)
            {
                result = DequeueNoWait();
            }

            this.mutex.ReleaseMutex();

            return(result);
        }
Esempio n. 13
0
        public void Dispatch(MessageDispatch dispatch)
        {
            try
            {
                MessageConsumer consumer = null;

                lock (this.consumers.SyncRoot)
                {
//                    if(this.consumers.Contains(dispatch.ConsumerId))
//                    {
//                        consumer = this.consumers[dispatch.ConsumerId] as MessageConsumer;
//                    }
                }

                // If the consumer is not available, just ignore the message.
                // Otherwise, dispatch the message to the consumer.
                if (consumer != null)
                {
                    consumer.Dispatch(dispatch);
                }
            }
            catch (Exception ex)
            {
                Tracer.DebugFormat("Caught Exception While Dispatching: {0}", ex.Message);
            }
        }
Esempio n. 14
0
        public void Dispatch(MessageDispatch messageDispatch)
        {
            // Auto ack messages when we reach 75% of the prefetch
            deliveredCounter++;

            if (deliveredCounter > (0.75 * this.info.PrefetchSize))
            {
                try
                {
                    MessageAck ack = new MessageAck();
                    ack.AckType        = (byte)AckType.ConsumedAck;
                    ack.FirstMessageId = messageDispatch.Message.MessageId;
                    ack.MessageCount   = deliveredCounter;

                    this.connection.Oneway(ack);
                    this.deliveredCounter = 0;
                }
                catch (Exception e)
                {
                    this.connection.OnAsyncException(e);
                }
            }

            DestinationInfo destInfo = messageDispatch.Message.DataStructure as DestinationInfo;

            if (destInfo != null)
            {
                ProcessDestinationInfo(destInfo);
            }
            else
            {
                // This can happen across networks
                Tracer.Debug("Unexpected message was dispatched to the AdvisoryConsumer: " + messageDispatch);
            }
        }
Esempio n. 15
0
        private MessageDispatchInfoContract CreateMessageDispatchInfoObj(MessageDispatch messageDispatch, Message message,
                                                                         bool senderCurrentUser)
        {
            WriteInfoLog("Creating message dispatch info contract.");

            string infomessage = string.Format("SenderName: {0}\n- ReceiverName: {1}" + "\n- SenderIsCurrentUser: {2}" +
                                               "\n- DispatchId: {3}" +
                                               "\n- MessageId: {4}", message.SenderEmailAddress,
                                               messageDispatch.EmailAddress,
                                               senderCurrentUser,
                                               messageDispatch.Id,
                                               message.Id);

            WriteInfoLog(infomessage);

            return(new MessageDispatchInfoContract
            {
                SenderName = message.SenderEmailAddress,
                ReceiverName = messageDispatch.EmailAddress,
                MessageSentDate = message.MessageCreated,
                MessageReceivedDate = messageDispatch.MessageReceivedTime,
                MessageReceived = messageDispatch.MessageReceived,
                MessageContent = message.MessageText,
                SenderCurrentUser = senderCurrentUser,
                DispatchId = messageDispatch.Id,
                MessageId = message.Id
            });
        }
Esempio n. 16
0
        protected void DoIndividualAcknowledge(MQTTMessage message)
        {
            MessageDispatch dispatch = null;

            lock (this.dispatchedMessages)
            {
                foreach (MessageDispatch originalDispatch in this.dispatchedMessages)
                {
                    if (originalDispatch.Message.MessageId.Equals(message.MessageId))
                    {
                        dispatch = originalDispatch;
                        this.dispatchedMessages.Remove(originalDispatch);
                        break;
                    }
                }
            }

            if (dispatch == null)
            {
                Tracer.DebugFormat("Attempt to Ack MessageId[{0}] failed because the original dispatch is not in the Dispatch List", message.MessageId);
                return;
            }

//			MessageAck ack = new MessageAck(dispatch, (byte) AckType.IndividualAck, 1);
//			Tracer.Debug("Sending Individual Ack for MessageId: " + ack.LastMessageId.ToString());
//			this.session.SendAck(ack);
        }
Esempio n. 17
0
 public virtual void AfterMessageIsConsumed(MessageDispatch dispatch, bool expired)
 {
     if (this.unconsumedMessages.Closed)
     {
         return;
     }
 }
Esempio n. 18
0
        private QueryBody GetDispatchInsertQuery(MessageDispatch dispatch)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter(MessageDispatchParameter.EMAIL_ADDRESS, dispatch.EmailAddress),
                new SqlParameter(MessageDispatchParameter.MESSAGE_ID, dispatch.MessageId),
                new SqlParameter(MessageDispatchParameter.MESSAGE_RECEIVED, GetDBValue(dispatch.MessageReceived)),
                new SqlParameter(MessageDispatchParameter.MESSAGE_RECEIVED_TIME, GetDBValue(dispatch.MessageReceivedTime))
            };

            string insertStatement = string.Format(@"INSERT INTO {0}({1}, {2}, {3}, {4})", TableName,
                                                   MessageDispatchColumn.EMAIL_ADDRESS,
                                                   MessageDispatchColumn.MESSAGE_ID,
                                                   MessageDispatchColumn.MESSAGE_RECEIVED,
                                                   MessageDispatchColumn.MESSAGE_RECEIVED_TIME);

            string valueSection = string.Format(@"VALUES ({0}, {1}, {2}, {3})",
                                                MessageDispatchParameter.EMAIL_ADDRESS,
                                                MessageDispatchParameter.MESSAGE_ID,
                                                MessageDispatchParameter.MESSAGE_RECEIVED,
                                                MessageDispatchParameter.MESSAGE_RECEIVED_TIME);

            string query = string.Format("{0} {1}", insertStatement, valueSection);

            return(new QueryBody(query, parameters));
        }
Esempio n. 19
0
        public void TestPeek()
        {
            MessageDispatchChannel channel   = new MessageDispatchChannel();
            MessageDispatch        dispatch1 = new MessageDispatch();
            MessageDispatch        dispatch2 = new MessageDispatch();

            Assert.IsTrue(channel.Empty == true);
            Assert.IsTrue(channel.Count == 0);

            channel.EnqueueFirst(dispatch1);

            Assert.IsTrue(channel.Empty == false);
            Assert.IsTrue(channel.Count == 1);

            channel.EnqueueFirst(dispatch2);

            Assert.IsTrue(channel.Empty == false);
            Assert.IsTrue(channel.Count == 2);

            Assert.IsTrue(channel.Peek() == null);

            channel.Start();

            Assert.IsTrue(channel.Peek() == dispatch2);
            Assert.IsTrue(channel.DequeueNoWait() == dispatch2);
            Assert.IsTrue(channel.Peek() == dispatch1);
            Assert.IsTrue(channel.DequeueNoWait() == dispatch1);
        }
Esempio n. 20
0
        public void DeleteDispatch(MessageDispatch dispatch)
        {
            try
            {
                SqlParameter[] sqlParameters = new SqlParameter[]
                {
                    new SqlParameter(MessageDispatchParameter.ID, GetDBValue(dispatch.Id))
                };

                string sqlQuery = string.Format("DELETE FROM {0} WHERE {1} = {2}", TableName,
                                                MessageDispatchColumn.ID,
                                                MessageDispatchParameter.ID);

                using (MssqlDbEngine mssqlDbEngine = GetMssqlDbEngine(sqlQuery, sqlParameters,
                                                                      connectionString))
                {
                    mssqlDbEngine.ExecuteQuery();
                }
            }
            catch (Exception exception)
            {
                string message = string.Format("Error encountered when executing {0} function in MessageDispatchRepositoryMsSql. Error\n{1}",
                                               "Deletedispatch", exception.Message);
                WriteErrorLog(message);
                throw;
            }
        }
Esempio n. 21
0
        public void TestDequeue()
        {
            MessageDispatchChannel channel = new MessageDispatchChannel();

            MessageDispatch dispatch1 = new MessageDispatch();
            MessageDispatch dispatch2 = new MessageDispatch();
            MessageDispatch dispatch3 = new MessageDispatch();

            channel.Start();
            Assert.IsTrue(channel.Running == true);

            DateTime timeStarted = DateTime.Now;

            Assert.IsTrue(channel.Dequeue(TimeSpan.FromMilliseconds(1000)) == null);

            DateTime timeFinished = DateTime.Now;

            TimeSpan elapsed = timeFinished - timeStarted;

            Assert.IsTrue(elapsed.TotalMilliseconds >= 999);

            channel.Enqueue(dispatch1);
            channel.Enqueue(dispatch2);
            channel.Enqueue(dispatch3);
            Assert.IsTrue(channel.Empty == false);
            Assert.IsTrue(channel.Count == 3);
            Assert.IsTrue(channel.Dequeue(TimeSpan.FromMilliseconds(Timeout.Infinite)) == dispatch1);
            Assert.IsTrue(channel.Dequeue(TimeSpan.Zero) == dispatch2);
            Assert.IsTrue(channel.Dequeue(TimeSpan.FromMilliseconds(1000)) == dispatch3);

            Assert.IsTrue(channel.Count == 0);
            Assert.IsTrue(channel.Empty == true);
        }
Esempio n. 22
0
        public void AfterMessageIsConsumed(MessageDispatch dispatch, bool expired)
        {
            if (this.unconsumedMessages.Closed)
            {
                return;
            }

            if (expired == true)
            {
                lock (this.dispatchedMessages)
                {
                    this.dispatchedMessages.Remove(dispatch);
                }

                // TODO - Not sure if we need to ack this in stomp.
                // AckLater(dispatch, AckType.ConsumedAck);
            }
            else
            {
                if (this.session.IsTransacted)
                {
                    // Do nothing.
                }
                else if (this.session.IsAutoAcknowledge)
                {
                    if (this.deliveringAcks.CompareAndSet(false, true))
                    {
                        lock (this.dispatchedMessages)
                        {
                            // If a Recover was called in the async handler then
                            // we don't want to send an ack otherwise the broker will
                            // think we consumed the message.
                            if (this.dispatchedMessages.Count > 0)
                            {
                                MessageAck ack = new MessageAck();

                                ack.AckType       = (byte)AckType.ConsumedAck;
                                ack.ConsumerId    = this.info.ConsumerId;
                                ack.Destination   = dispatch.Destination;
                                ack.LastMessageId = dispatch.Message.MessageId;
                                ack.MessageCount  = 1;

                                this.session.SendAck(ack);
                            }
                        }

                        this.deliveringAcks.Value = false;
                        this.dispatchedMessages.Clear();
                    }
                }
                else if (this.session.IsClientAcknowledge || this.session.IsIndividualAcknowledge)
                {
                    // Do nothing.
                }
                else
                {
                    throw new NMSException("Invalid session state.");
                }
            }
        }
Esempio n. 23
0
 public void Dispatch(MessageDispatch dispatch)
 {
     if (this.executor != null)
     {
         this.executor.Execute(dispatch);
     }
 }
        public async System.Threading.Tasks.Task DispatchAsync(MessageDispatch dispatch)
        {
            try
            {
                MessageConsumer consumer = null;

                lock (this.consumers.SyncRoot)
                {
                    if (this.consumers.Contains(dispatch.ConsumerId))
                    {
                        consumer = this.consumers[dispatch.ConsumerId] as MessageConsumer;
                    }
                }

                // If the consumer is not available, just ignore the message.
                // Otherwise, dispatch the message to the consumer.
                if (consumer != null)
                {
                    await consumer.Dispatch_Async(dispatch).Await();
                }
            }
            catch (Exception ex)
            {
                Tracer.DebugFormat("Caught Exception While Dispatching: {0}", ex.Message);
            }
        }
Esempio n. 25
0
        private void DoIndividualAcknowledge(Message message)
        {
            MessageDispatch dispatch = null;

            lock (_dispatchedMessages)
                foreach (var originalDispatch in _dispatchedMessages.Where(originalDispatch => originalDispatch.Message.MessageId.Equals(message.MessageId)))
                {
                    dispatch = originalDispatch;
                    _dispatchedMessages.Remove(originalDispatch);
                    break;
                }

            if (dispatch == null)
            {
                Tracer.WarnFormat("Attempt to Ack MessageId[{0}] failed because the original dispatch is not in the Dispatch List", message.MessageId);
                return;
            }

            var ack = new MessageAck
            {
                AckType       = (Byte)AckType.IndividualAck,
                ConsumerId    = ConsumerInfo.ConsumerId,
                Destination   = dispatch.Destination,
                LastMessageId = dispatch.Message.MessageId,
                MessageCount  = 1
            };

            _session.SendAck(ack);
        }
        private ActiveMQMessage CreateActiveMQMessage(MessageDispatch dispatch)
        {
            ActiveMQMessage message = dispatch.Message.Clone() as ActiveMQMessage;

            if (this.ConsumerTransformer != null)
            {
                IMessage newMessage = ConsumerTransformer(this.session, this, message);
                if (newMessage != null)
                {
                    message = this.messageTransformation.TransformMessage <ActiveMQMessage>(newMessage);
                }
            }

            message.Connection = this.session.Connection;

            if (IsClientAcknowledge)
            {
                message.Acknowledger += new AcknowledgeHandler(DoClientAcknowledge);
            }
            else if (IsIndividualAcknowledge)
            {
                message.Acknowledger += new AcknowledgeHandler(DoIndividualAcknowledge);
            }
            else
            {
                message.Acknowledger += new AcknowledgeHandler(DoNothingAcknowledge);
            }

            return(message);
        }
Esempio n. 27
0
        protected void DispatchMessage(MessageDispatch dispatch)
        {
            lock (dispatchers.SyncRoot)
            {
                if (dispatchers.Contains(dispatch.ConsumerId))
                {
                    IDispatcher dispatcher = (IDispatcher)dispatchers[dispatch.ConsumerId];

                    // Can be null when a consumer has sent a MessagePull and there was
                    // no available message at the broker to dispatch or when signalled
                    // that the end of a Queue browse has been reached.
                    if (dispatch.Message != null)
                    {
                        dispatch.Message.ReadOnlyBody       = true;
                        dispatch.Message.ReadOnlyProperties = true;
                        dispatch.Message.RedeliveryCounter  = dispatch.RedeliveryCounter;
                    }

                    dispatcher.Dispatch(dispatch);

                    return;
                }
            }

            Tracer.ErrorFormat("Connection[{0}]: No such consumer active: {1}", this.ConnectionId, dispatch.ConsumerId);
        }
        public IMessage ReceiveNoWait()
        {
            CheckClosed();
            CheckMessageListener();

            MessageDispatch dispatch = null;

            SendPullRequest(-1);

            if (this.PrefetchSize == 0)
            {
                dispatch = this.Dequeue(TimeSpan.FromMilliseconds(-1));
            }
            else
            {
                dispatch = this.Dequeue(TimeSpan.Zero);
            }

            if (dispatch == null)
            {
                return(null);
            }

            BeforeMessageIsConsumed(dispatch);
            AfterMessageIsConsumed(dispatch, false);

            return(CreateActiveMQMessage(dispatch));
        }
        private Message CreateStompMessage(MessageDispatch dispatch)
        {
            Message message = dispatch.Message.Clone() as Message;

            if (this.ConsumerTransformer != null)
            {
                IMessage transformed = this.consumerTransformer(this.session, this, message);
                if (transformed != null)
                {
                    message = this.messageTransformation.TransformMessage <Message>(transformed);
                }
            }

            message.Connection = this.session.Connection;

            if (this.session.IsClientAcknowledge)
            {
                message.Acknowledger += new AcknowledgeHandler(DoClientAcknowledge);
            }
            else if (this.session.IsIndividualAcknowledge)
            {
                message.Acknowledger += new AcknowledgeHandler(DoIndividualAcknowledge);
            }
            else
            {
                message.Acknowledger += new AcknowledgeHandler(DoNothingAcknowledge);
            }

            return(message);
        }
Esempio n. 30
0
    public void UnRegisterReceiver()
    {
        #region Event
        EventDispatch.UnRegisterReceiver <int>(EventID.Ready_Request, OnReadyRequest);
        EventDispatch.UnRegisterReceiver <EventConnect>(EventID.Connect_Request, OnConnectRequest);
        EventDispatch.UnRegisterReceiver <Command>(EventID.AddCommand, OnAddCommand);
        #endregion
        #region Message
        MessageDispatch.UnRegisterReceiver <GM_Accept>(MessageID.GM_ACCEPT_SC, OnAccept);
        MessageDispatch.UnRegisterReceiver <GM_Connect>(MessageID.GM_CONNECT_SC, OnConnectReturn);
        MessageDispatch.UnRegisterReceiver <GM_Connect>(MessageID.GM_CONNECT_BC, OnConnectBC);
        MessageDispatch.UnRegisterReceiver <GM_Disconnect>(MessageID.GM_DISCONNECT_BC, OnDisconnectBC);
        MessageDispatch.UnRegisterReceiver <GM_Ready>(MessageID.GM_READY_BC, OnReadyBC);
        MessageDispatch.UnRegisterReceiver <GM_Begin>(MessageID.GM_BEGIN_BC, OnBeginBC);
        MessageDispatch.UnRegisterReceiver <GM_Frame_BC>(MessageID.GM_FRAME_BC, OnFrameBC);
        MessageDispatch.UnRegisterReceiver <GM_Return>(MessageID.GM_PING_SC, OnPingReturn);

        #endregion

        #region Command
        CommandDispatch.UnRegisterReceiver <CMD_ReleaseSkill>(CommandID.RELEASE_SKILL, OnCommandReleaseSkill);
        CommandDispatch.UnRegisterReceiver <CMD_MoveToPoint>(CommandID.MOVE_TO_POINT, OnCommandMoveToPoint);
        CommandDispatch.UnRegisterReceiver <CMD_CreateMonster>(CommandID.CREATE_MONSTER, OnCreateMonster);
        #endregion
    }
Esempio n. 31
0
        public void MessageDispatch_Test_Dispatch()
        {
            MessageDispatch dispatch = new MessageDispatch();
            MessageBuilder builder1 = new MessageBuilder();
            builder1.SetAddress("/test1");
            builder1.PushAtom(1);

            MessageBuilder builder2 = new MessageBuilder();
            builder2.SetAddress("/test2");
            builder2.PushAtom("TEST");

            MessageBuilder builder3 = new MessageBuilder();
            builder3.SetAddress("/test3");
            builder3.PushAtom("TEST2");

            String address = "";
            Atom value = new Atom();

            Action<osc.net.Message> callback = m => {
                address = m.Address;
                value = m.Atoms[0];
            };

            dispatch.RegisterMethod("/test1", callback);
            dispatch.RegisterMethod("/test2", callback);

            // Test
            dispatch.Dispatch(builder1.ToMessage());
            Assert.AreEqual("/test1", address);
            Assert.AreEqual(1, value);

            dispatch.Dispatch(builder2.ToMessage());
            Assert.AreEqual("/test2", address);
            Assert.AreEqual("TEST", value);

            // No callback registered, values should not be set
            dispatch.Dispatch(builder3.ToMessage());
            Assert.AreNotEqual("/test3", address);
            Assert.AreNotEqual("TEST2", value);
        }
Esempio n. 32
0
        /// <summary>
        /// Called on a background thread to raise an event indicating that a message has been picked up.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessAndDispatchMessageQueueItem(MessageDispatch message)
        {
            if(message.Port30003MessageEventArgs != null) {
                OnPort30003MessageReceived(message.Port30003MessageEventArgs);
            } else if(message.RawBytesEventArgs != null) {
                OnRawBytesReceived(message.RawBytesEventArgs);
            } else if(message.ModeSBytesEventArgs != null) {
                OnModeSBytesReceived(message.ModeSBytesEventArgs);
            } else {
                var modeSMessageArgs = message.ModeSMessageEventArgs;
                OnModeSMessageReceived(modeSMessageArgs);

                BaseStationMessage cookedMessage;
                lock(_SyncLock) {
                    cookedMessage = RawMessageTranslator == null ? null : RawMessageTranslator.Translate(modeSMessageArgs.ReceivedUtc, modeSMessageArgs.ModeSMessage, modeSMessageArgs.AdsbMessage);
                }
                if(cookedMessage != null) OnPort30003MessageReceived(new BaseStationMessageEventArgs(cookedMessage));
            }
        }
Esempio n. 33
0
 internal void RegisterMsgHandler(RoomMessageDefine id, MessageDispatch.MsgHandler handler)
 {
     m_Dispatch.RegisterHandler(id, handler);
 }
Esempio n. 34
0
 public static MessageDispatch getInstance()
 {
     if (m_instance == null)
          return m_instance = new MessageDispatch();
      return m_instance;
 }
Esempio n. 35
0
 public GameManager(MessageDispatch dispatcher)
 {
     _dispatcher = dispatcher;
     BackgroundColor = Color.FromArgb(255, 0, 128, 0);
 }