Example #1
0
        private void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            if (OnMessageReceived == null) return;

            var transaction = new MessageQueueTransaction();
            transaction.Begin();

            try
            {
                var queueMessage = inputQueue.Receive(transaction);
                var headers = GetMessageHeaders(queueMessage);
                var message = new ChannelMessage(queueMessage.BodyStream);
                message.AddHeader(headers);
                OnMessageReceived(this, new MessageReceivedEventArgs { Message = message });
                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Abort();
                throw;
            }
            finally
            {
                inputQueue.BeginPeek();
            }
        }
Example #2
0
        static void _orderQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            var orderQueue = (MessageQueue)sender;

            var transaction = new MessageQueueTransaction();
            transaction.Begin();

            Order order;

            try
            {
                var receivedMessage = orderQueue.Receive(transaction);
                receivedMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                order = Order.DeserializeXml(receivedMessage.Body.ToString());

                using (var db = new OrderContext())
                {
                    db.Orders.Add(order);
                    db.SaveChanges();
                }

                transaction.Commit();
            }
            catch
            {
                // TODO: Log something
                transaction.Abort();
            }
            finally
            {
                orderQueue.BeginPeek();
            }
        }
        private void QueuePeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            Message message = _queue.EndPeek(e.AsyncResult);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\nA message was read from the Sales queue.");
            Console.WriteLine(string.Format("The message was: {0}", message.Body));

            _queue.Receive();
            _queue.BeginPeek();
        }
        private void DelegatePeekCompleted(object sender, CompletedEventArgs args)
        {
            if (PeekCompleted == null)
            {
                return;
            }

            PeekCompletedEventArgs newArgs = new PeekCompletedEventArgs(this, args.AsyncResult);

            PeekCompleted(sender, newArgs);
        }
        private void MessageAvailable(object source, PeekCompletedEventArgs args)
        {
            var messageQueue = (MessageQueue) source;

            try
            {
                ReadMessage(messageQueue);
            }
            finally
            {
                messageQueue.Close();
            }

            // Continue reading from the queue
            messageQueue.BeginPeek();
        }
        /// <summary>
        /// Peek completed event
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="eventArg">Event argument</param>
        private void PeekCompleted(object sender, System.Messaging.PeekCompletedEventArgs eventArg)
        {
            object message = new object();

            ((MessageQueue)sender).EndPeek(eventArg.AsyncResult);

            if (this.IsTransactional)
            {
                message = this.ReceiveMessageTransactional((MessageQueue)sender);
            }
            else
            {
                message = this.ReceiveMessage((MessageQueue)sender);
            }

            this.MessageQueuesProcessed(this, new EngineEventArgs(new object[] { message }));
        }
Example #7
0
        private void receiveQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            MessageQueue mq = (MessageQueue)sender;

            // End the asynchronous Receive operation.
            mq.EndPeek(e.AsyncResult);

            if (!started)
            {
                return;
            }

            var message = mq.Receive();
            DispatchMessage(message);

            mq.BeginPeek();
        }
Example #8
0
 private void OnMessagePeeked(object sender, PeekCompletedEventArgs e)
 {
     var transaction = new MessageQueueTransaction();
     try
     {
         transaction.Begin();
         var message = _messageQueue.Receive(transaction);
         MessageReceived(this, new MessageReceivedEventArgs(message));
     }
     catch
     {
         transaction.Abort();
         throw;
     }
     finally
     {
         transaction.Dispose();
     }
 }
Example #9
0
        public void readAndPeek(object sender, PeekCompletedEventArgs args)
        {
            MessageQueue queue = (MessageQueue)sender;
            try
            {
                this.logger.WriteEntry("started peek on " + Reservation.QUEUE_PATH);

                Message msg = queue.EndReceive(args.AsyncResult);
                msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(Reservation) });
                Reservation reservation = (Reservation)msg.Body;
                this.logger.WriteEntry("found hotel " + reservation.Hotel.HotelId);
                saveReservation(reservation);
                queue.Receive();
                this.logger.WriteEntry("peek done");
            }
            catch (Exception e)
            {
                this.logger.WriteEntry(e.Message);
            }
            queue.BeginPeek();
        }
 private void TxQueueOnPeekCompleted(object sender, PeekCompletedEventArgs peekCompletedEventArgs)
 {
     if (_stopRequested) return;
     _stopReady = false;
     var txQueue = (MessageQueue) sender;
     using (var tx = new MessageQueueTransaction())
     {
         try
         {
             tx.Begin();
             using (Message currentMessage = txQueue.Receive(tx))
             {
                 Thread.Sleep(2500); // some process
             }
             tx.Commit();
         }
         catch (Exception)
         {
             tx.Abort(); // puts message back on the queue
         }
     }
     _stopReady = true;
     if (!_stopRequested) txQueue.BeginPeek();
 }
        private void queue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            var queue = (MessageQueue)sender;

            var transaction = new MessageQueueTransaction();
            transaction.Begin();
            try
            {
                var message = queue.Receive(transaction);
                var tm = NServiceBus.Utils.MsmqUtilities.Convert(message);
                var audit = tm.To_NServiceBus_Audit_Message();
                Bus.SendLocal(audit);

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Abort();
            }
            finally
            {
                queue.BeginPeek();
            }
        }
Example #12
0
        void OnPeekCompleted(object sender, PeekCompletedEventArgs peekCompletedEventArgs)
        {
            stopResetEvent.Reset();

            CallPeekWithExceptionHandling(() => queue.EndPeek(peekCompletedEventArgs.AsyncResult));

            throttlingSemaphore.Wait();

            WorkerTaskFactory.Start(Action, CancellationToken.None);

            //We using an AutoResetEvent here to make sure we do not call another BeginPeek before the Receive has been called
            peekResetEvent.WaitOne();

            CallPeekWithExceptionHandling(() => queue.BeginPeek());

            stopResetEvent.Set();
        }
 private void MonitoredQueueOnPeekCompleted(object sender, PeekCompletedEventArgs peekCompletedEventArgs)
 {
     lock (_threadLock)
     {
         if (_stopRequested) return;
         using (var tx = new MessageQueueTransaction())
         {
             tx.Begin();
             try
             {
                 using (Message message = _monitoredQueue.Receive(tx))
                 {
                     if (message != null)
                     {
                         ProcessMessage(tx, message);
                     }
                 }
                 tx.Commit();
             }
             catch (Exception)
             {
                 tx.Abort();
             }
         }
         if (!_stopRequested) _monitoredQueue.BeginPeek();
     }
 }
Example #14
0
		private void HandleMessage (object source, PeekCompletedEventArgs args) {
			eventCalled = true;
		}
Example #15
0
        private void Manager(object source, PeekCompletedEventArgs asyncResult)
        {
            // Connect to the queue.
            MessageQueue mq = source as MessageQueue;

            try
            {
                // The manager has responsibility to delegate a work to the receiver for incomming messages
                // The number of the workers can be managed administratively or on the fly.

                // End the asynchronous peek operation.
                mq.EndPeek(asyncResult.AsyncResult);

                // threadpool controller
                while(true)
                {
                    // wait for condition (workers are ready, etc.)
                    if(m_EventMgr.WaitOne(NotifyTime * 1000, true) == false)
                    {
                        // timeout handler
                        if(MaxNumberOfWorkers > 0)
                        {
                            string strWarning = string.Format("[{0}]MSMQChannel.Receiver: All Message Workers are busy", ChannelName);
                            WriteLogMsg(strWarning, EventLogEntryType.Warning);

                            // threadpool is closed, try again
                            continue;
                        }
                        else
                        {
                            m_Listening = false;
                            return;
                        }
                    }

                    // threadpool is open
                    break;
                }

                // delegate work to the worker
                MessageWorkerDelegator mwd = new MessageWorkerDelegator(MessageWorker);
                mwd.BeginInvoke(source, null, null);

            }
            catch(Exception ex)
            {
                string strErr = string.Format("[{0}]MSMQChannel.Receiver:Mamager failed, error = {1}", ChannelName, ex.Message);
                WriteLogMsg(strErr, EventLogEntryType.Error);
            }
            finally
            {
                // Restart the asynchronous peek operation
                if(m_Listening == true)
                    mq.BeginPeek();
                else
                    Trace.WriteLine(string.Format("[{0}]MSMQChannel.Receiver.Manager has been disconnected", ChannelName));
            }
        }
        void QueueOnPeekCompleted(object sender, PeekCompletedEventArgs args)
        {
            stopResetEvent.Reset();

            TryStartNewBatchImporter();
        }
Example #17
0
        private void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            Message message = null;
            var messageQueueTransaction = new MessageQueueTransaction();
            try
            {
                var messageQueue = (MessageQueue)sender;
                messageQueue.EndPeek(e.AsyncResult);

                messageQueueTransaction.Begin();
                message = messageQueue.Receive(messageQueueTransaction);
                messageQueueTransaction.Commit();
            }
            catch (Exception ex)
            {
                messageQueueTransaction.Abort();
                Debug.WriteLine("Exception:ReceiveMessage Exception:" + ex);
            }

            if (message != null)
            {
                var messageObj = (MessageObj)message.Body;
                Debug.WriteLine("Async Receive Message Done!(" + messageObj.MediaTaskId + ")");
            }
        }
        void queue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            var queue = sender as MessageQueue;
            if (e.Message == null || queue == null)
                return;

            Bus.Publish(new Queue_Alarm
            {
                Id= Guid.NewGuid(),
                Timestamp = DateTime.Now,
                Queue_Name = queue.FormatName
            });
        }
Example #19
0
        private void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            Debug.WriteLine("Peek Complete!");
            queue.EndPeek(e.AsyncResult);
            var transaction = new MessageQueueTransaction();
            try {
                transaction.Begin();
                var msg = queue.Receive(transaction);
                transaction.Commit();

                StartListening();

                FireRecieveEvent(msg);
            }
            catch(Exception ex) {
                if(transaction.Status == MessageQueueTransactionStatus.Pending)
                    transaction.Abort();

                Debug.WriteLine("Peek Exception: {0}", ex.Message);
            }
        }
        void OnPeekCompleted(object sender, PeekCompletedEventArgs peekCompletedEventArgs)
        {
            stopResetEvent.Reset();

            CallPeekWithExceptionHandling(() => queue.EndPeek(peekCompletedEventArgs.AsyncResult));

            throttlingSemaphore.Wait();

            Task.Factory
                .StartNew(Action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                .ContinueWith(task =>
                {
                    task.Exception.Handle(ex =>
                    {
                        Logger.Error("Error processing message.", ex);
                        return true;
                    });
                }, TaskContinuationOptions.OnlyOnFaulted);

            //We using an AutoResetEvent here to make sure we do not call another BeginPeek before the Receive has been called
            peekResetEvent.WaitOne();

            CallPeekWithExceptionHandling(() => queue.BeginPeek());

            stopResetEvent.Set();
        }
Example #21
0
        private void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            _queue.EndPeek(e.AsyncResult);
            var trans = new MessageQueueTransaction();
            Message msg = null;
            try
            {
                trans.Begin();
                msg = _queue.Receive(trans);
                trans.Commit();

                StartListening();

                FireRecieveEvent(msg.Body);
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex);
                trans.Abort();
            }
        }
Example #22
0
		private void DelegatePeekCompleted (object sender, CompletedEventArgs args)
		{
			if (PeekCompleted == null)
				return;
			
			PeekCompletedEventArgs newArgs = new PeekCompletedEventArgs (this, args.AsyncResult);			
			PeekCompleted (sender, newArgs);
		}
        void workflowQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            MessageQueue workflowQueue = (MessageQueue)sender;
            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    Message queueMessage = workflowQueue.Receive(MessageQueueTransactionType.Automatic);
                    Task.Factory.StartNew(() => RunFrameworkJob(queueMessage, null));
                    Interlocked.Increment(ref JobsRunning);
                    txScope.Complete();
                }
                catch (MessageQueueException ex)
                {
                    Interlocked.Decrement(ref JobsRunning);
                    pool.Release();
                    if (ex.MessageQueueErrorCode == MessageQueueErrorCode.QueueNotAvailable)
                        LoadActiveQueue();
                    else
                        throw new WorkflowException("Error getting framework job from queue: An internal Message Queuing error occured", ex);
                }
                catch (InvalidOperationException ex)
                {
                    Interlocked.Decrement(ref JobsRunning);
                    pool.Release();
                    throw new WorkflowException("Error begining transaction: The transaction has already been started.", ex);
                }
                catch (Exception ex)
                {
                    Interlocked.Decrement(ref JobsRunning);
                    pool.Release();
                    throw new WorkflowException("General Error Starting Framework Job.", ex);
                }
            }

            if (!StopProcess)
            {
                pool.WaitOne();
                workflowQueue.BeginPeek();
            }
        }
Example #24
0
        private void RetryManager(object source, PeekCompletedEventArgs asyncResult)
        {
            // the message is going to move using the transactional manner
            MessageQueueTransaction mqtx = null;

            // Connect to the queue.
            MessageQueue mq = (MessageQueue)source;

            try
            {
                // End the asynchronous peek operation.
                Message msg = mq.EndPeek(asyncResult.AsyncResult);

                // check the message lifetime
                DateTime elapsedTime = msg.ArrivedTime.AddSeconds(RetryTime);

                if(DateTime.Compare(DateTime.Now, elapsedTime) >= 0)
                {
                    // it's the time to move it
                    // create destination queue
                    MessageQueue InQueue = new MessageQueue(ListenerPath);
                    InQueue.Formatter = new BinaryMessageFormatter();
                    mqtx = new MessageQueueTransaction();

                    // echo
                    Trace.WriteLine(string.Format("[{0}]MSMQChannel.Receiver.RetryManager - Moveing message \"{1}\"", ChannelName, msg.Label));

                    // move it
                    mqtx.Begin();
                    Message msgToMove = mq.Receive(new TimeSpan(0,0,0,1));
                    InQueue.Send(msgToMove, mqtx);
                    mqtx.Commit();
                }
                else
                {
                    // it's the time to sleep
                    TimeSpan deltaTime = elapsedTime.Subtract(DateTime.Now);

                    // the sleep time
                    int sleeptime =  Convert.ToInt32(deltaTime.TotalMilliseconds);

                    // echo
                    Trace.WriteLine(string.Format("[{0}]MSMQChannel.Receiver.RetryManager - Sleeping for {1}ms", ChannelName, sleeptime));

                    // wait for timeout or signal such as change retrytime value or shutdown process
                    m_EventRetryMgr.WaitOne(sleeptime, true);
                }
            }
            catch(Exception ex)
            {
                if(mqtx != null && mqtx.Status == MessageQueueTransactionStatus.Pending)
                    mqtx.Abort();

                string strErr = string.Format("[{0}]MSMQChannel.Receiver:RetryMamager failed, error = {1}", ChannelName, ex.Message);
                WriteLogMsg(strErr, EventLogEntryType.Error);
            }
            finally
            {
                // Restart the asynchronous peek operation
                if(m_RetryListening == true)
                    mq.BeginPeek();
                else
                    Trace.WriteLine(string.Format("[{0}]MSMQChannel.Receiver.RetryManager has been disconnected", ChannelName));
            }
        }
Example #25
0
        void mobjInboundQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            Message objMessage = null;

            try
            {
                // Get Message from Queue
                objMessage = mobjInboundQueue.EndPeek(e.AsyncResult);

                if (BeginReceivePreRaisingLastMessageReceivedEvent)
                {
                    // Listen for further messages
                    mobjInboundQueue.BeginPeek();
                    // Expose Message to hosting instance
                    MessageReceived(objMessage, true, mobjInboundQueue.Path);
                }
                else
                {
                    // Expose Message to hosting instance
                    MessageReceived(objMessage, true, mobjInboundQueue.Path);
                    // Listen for further messages
                    mobjInboundQueue.BeginPeek();
                }
            }
            catch (NullReferenceException)
            {
                if (mobjInboundQueue != null)
                {
                    // Ignore
                }
            }
            catch (MessageQueueException excE)
            {
                throw excE;
            }
            catch (Exception excE)
            {
                throw excE;
            }
        }