public List <T> PeekAllMessagePayloads(int timeoutSeconds)
        {
            var        list   = new List <T>();
            Cursor     cursor = _messageQueue.CreateCursor();
            PeekAction action = PeekAction.Current;
            Message    message;

            try
            {
                while ((message = _messageQueue.Peek(TimeSpan.FromSeconds(timeoutSeconds), cursor, action)) != null)
                {
                    list.Add((T)message.Body);
                    action = PeekAction.Next;
                }
            }
            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    return(list);
                }
                Debug.WriteLine(e);
                throw;
            }

            return(list);
        }
        private void buttonPollForRequest_Click(object sender, EventArgs e)
        {
            string       remoteq = @"FormatName:direct=OS:provsvc\private$\Provision";
            MessageQueue rq      = new MessageQueue(remoteq);

            System.Messaging.Cursor cursor = rq.CreateCursor();
            TimeSpan timeout = new TimeSpan(0, 0, 10);

            rq.Formatter = new XmlMessageFormatter(new[] { typeof(ProvisionTask) });

            System.Messaging.Message m;
            PeekAction action = PeekAction.Current;

            m = GetPeek(rq, cursor, PeekAction.Current);

            while (m != null)
            {
                ProvisionTask r = (ProvisionTask)m.Body;
                if (r.target.ToLower() == Environment.MachineName.ToLower())
                {
                    m = GetMessage(rq, m.Id);
                }
                m = GetPeek(rq, cursor, PeekAction.Next);
            }



            cursor.Close();
        }
        public List <ReceiveResponse <T> > PeekAllMessages(int timeoutSeconds)
        {
            List <ReceiveResponse <T> > list = new List <ReceiveResponse <T> >();
            Cursor     cursor = _messageQueue.CreateCursor();
            PeekAction action = PeekAction.Current;
            Message    message;

            try
            {
                while ((message = _messageQueue.Peek(TimeSpan.FromSeconds(timeoutSeconds), cursor, action)) != null)
                {
                    ReceiveResponse <T> response = new ReceiveResponse <T>(false, (T)message.Body, message.Label, message.Id);
                    list.Add(response);
                    action = PeekAction.Next;
                }
            }
            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    return(list);
                }
                Debug.WriteLine(e);
                throw;
            }

            return(list);
        }
Esempio n. 4
0
        /// <summary>
        /// Instantiate a new instance of MSMQMessageFetcher class.
        /// </summary>
        /// <param name="messageQueue">target MSMQ queue</param>
        /// <param name="messageCount">number of messages in queue</param>
        /// <param name="messageFormatter">message formatter for deserializing MSMQ message</param>
        /// <param name="prefetchCacheCapacity">prefetch cache capacity</param>
        /// <param name="maxOutstandingFetchCount">maximun number of outstanding BeginPeek operations</param>
        public MSMQMessageFetcher(MessageQueue messageQueue, long messageCount, IMessageFormatter messageFormatter, int prefetchCacheCapacity, int maxOutstandingFetchCount)
        {
            this.msmqQueueField           = messageQueue;
            this.msmqMessageCount         = messageCount;
            this.messageFormatter         = messageFormatter;
            this.prefetchCacheCapacity    = prefetchCacheCapacity;
            this.maxOutstandingFetchCount = maxOutstandingFetchCount;
            this.prefetchCredit           = this.prefetchCacheCapacity;

            this.messagePeekCursorField   = new RefCountedCursor(this.msmqQueueField.CreateCursor());
            this.messagePeekActionField   = PeekAction.Current;
            this.msmqQueueField.Disposed += this.OnQueueDisposed;

            this.prefetchTimer.AutoReset = false;
            this.prefetchTimer.Interval  = 500;
            this.prefetchTimer.Elapsed  += (sender, args) =>
            {
                Debug.WriteLine("[MSMQMessageFetcher] .prefetchTimer raised.");
                this.PeekMessage();
                if (!this.isDisposedField)
                {
                    this.prefetchTimer.Enabled = true;
                }
            };
            this.prefetchTimer.Enabled = true;

            BrokerTracing.TraceVerbose("[MSMQMessageFetcher] .Create new instance: prefetchCacheCapacity={0}, maxOutstandingFetchCount={1}", this.prefetchCacheCapacity, this.maxOutstandingFetchCount);
        }
 System.Messaging.Message GetPeek(MessageQueue q, System.Messaging.Cursor c, PeekAction action)
 {
     System.Messaging.Message ret = null;
     try
     {
         ret = q.Peek(new TimeSpan(1), c, action);
     }
     catch (Exception ex)
     {
         Log(ex.Message);
     }
     return(ret);
 }
Esempio n. 6
0
        private Message PeekMessage(MessageQueue queue, Cursor cursor, PeekAction action)
        {
            ResetUnderlyingMessageData();

            try
            {
                underlyingMessageData = queue.Peek(timeout, cursor, action);

                return((Message)underlyingMessageData);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 7
0
 private static Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
 {
     Message ret = null;
     try
     {
         ret = q.Peek(new TimeSpan(1), cursor, action);
     }
     catch (MessageQueueException mqe)
     {
         if (!mqe.Message.ToLower().Contains("timeout"))
         {
             throw;
         }
     }
     return ret;
 }
Esempio n. 8
0
        static Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
        {
            Message ret = null;

            try
            {
                ret = q.Peek(new TimeSpan(1), cursor, action);
            }
            catch (MessageQueueException mqe)
            {
                if (!mqe.Message.ToLower().Contains("timeout"))
                {
                    throw;
                }
            }
            return(ret);
        }
Esempio n. 9
0
        protected Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
        {
            Message ret = null;

            try
            {
                ret = q.Peek(new TimeSpan(1), cursor, action);
            }
            catch (MessageQueueException mqe)
            {
                if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                {
                    throw;
                }
            }
            return(ret);
        }
Esempio n. 10
0
        /// <summary>
        /// Returns without removing (peeks) the first message in the queue
        /// referenced by this MessageQueue, matching the selection criteria.
        /// </summary>
        /// <param name="maxTime">Reception time-out.</param>
        /// <param name="convertBody">true if message body should be converted.</param>
        /// <returns>Peeked message.</returns>
        private IMessage InternalPeek(DateTime maxTime, bool convertBody)
        {
            TimeSpan timeSpan = maxTime - DateTime.Now;

            if (timeSpan <= TimeSpan.Zero)
            {
                timeSpan = TimeSpan.Zero;
            }

            using (Cursor cursor = messageQueue.CreateCursor())
            {
                PeekAction action = PeekAction.Current;
                while (true)
                {
                    Message msmqMessage = null;

                    try
                    {
                        msmqMessage = messageQueue.Peek(timeSpan, cursor, action);
                    }
                    catch (MessageQueueException exc)
                    {
                        if (exc.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                        {
                            return(null);
                        }
                        throw exc;
                    }

                    IMessage nmsMessage = InternalMatch(msmqMessage, convertBody);

                    if (nmsMessage != null)
                    {
                        return(nmsMessage);
                    }

                    action = PeekAction.Next;
                }
            }
        }
Esempio n. 11
0
        public static bool HandleAsyncCallbackError(MessageQueueException e, ref PeekAction peekAction, string format, params object[] objParams)
        {
            bool needRetry = false;

            if (e.MessageQueueErrorCode == MessageQueueErrorCode.IllegalCursorAction ||
                e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
            {
                // the cursor is moved to the end of the queue, then the need set the peek action to peek the new come in messages.
                needRetry  = true;
                peekAction = PeekAction.Current;
            }
            else if (e.MessageQueueErrorCode == MessageQueueErrorCode.OperationCanceled)
            {
                // Question: Can a thread performs an asynchronous Receive call and then exits?
                //    No. This can lead to the cancellation of the Receive call. A thread which makes an asynchronous Receive call (either receive with callback or receive with overlap) must be alive as long as the Receive call is pending in the MSMQ driver. If the thread terminates and exits before the Receive call completes then the Receive operation is cancelled and the application gets back the error code 0xc0000120 (STATUS_CANCELLED).
                // For VB/COM code, this means that a thread which calls EnableNotification must be alive until the Arrived (or ArrivedError) events are called.
                // For .NET framework, this means that a thread which calls BeginPeek or BeginReceive must be alive until the completion delegate is called.
                // It is legitimate to terminate the calling thread before the Receive operation is completed if the callback (or notification) code is designed to accept and handle the STATUS_CANCELLED error.
                // the MSMQPersist does not use the dedicated thread to peek the responses or requests from the message queue. but the threadpool maybe shrink and some threads in the pool that have pending peek operation exit will cancel the pending peek/receive operation.
                // so, need retry the peek/receive operation when OperationCanceled exception raised.
                needRetry = true;
            }

            if (needRetry)
            {
                string errorMessage = string.Empty;
                if (!string.IsNullOrEmpty(format))
                {
                    errorMessage = string.Format(format, objParams) + ", and";
                }

                errorMessage += " the exception: " + e.ToString();
                BrokerTracing.TraceInfo(errorMessage);
            }

            return(needRetry);
        }
Esempio n. 12
0
        private bool Run(PeekAction action)
        {
            try
            {
                Message = Read((int)action);

                if (Message != null)
                {
                    _messagesRead++;
                }

                return(true);
            }
            catch (MessageQueueException ex)
            {
                //If there were no more messages to read this exception will be thrown at which point command execution can be considered complete
                if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    _complete = true; //Update status to complete

                    _cursor.Close();

                    return(true); //We are done at this point
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, errorMessage, Path, ex.Message);

                return(false);
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Initiates an asynchronous peek operation that has a specified time-out and that uses a specified cursor, a specified peek action, and a specified state object. The state object provides associated information throughout the lifetime of the operation. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
 /// </summary>
 /// <returns>
 /// The <see cref="T:System.IAsyncResult"/> that identifies the posted asynchronous request.
 /// </returns>
 /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that indicates the interval of time to wait for a message to become available. </param><param name="cursor">A <see cref="T:System.Messaging.Cursor"/> that maintains a specific position in the message queue.</param><param name="action">One of the <see cref="T:System.Messaging.PeekAction"/> values. Indicates whether to peek at the current message in the queue, or the next message.</param><param name="state">A state object, specified by the application, that contains information associated with the asynchronous operation. </param><param name="callback">The <see cref="T:System.AsyncCallback"/> that receives the notification of the asynchronous operation completion. </param><exception cref="T:System.ArgumentOutOfRangeException">A value other than PeekAction.Current or PeekAction.Next was specified for the <paramref name="action"/> parameter.</exception><exception cref="T:System.ArgumentNullException">The <paramref name="cursor"/> parameter is null.</exception><exception cref="T:System.ArgumentException">The value specified for the <paramref name="timeout"/> parameter is not valid. </exception><exception cref="T:System.Messaging.MessageQueueException">An error occurred when accessing a Message Queuing method. </exception>
 public IAsyncResult BeginPeek(TimeSpan timeout, Cursor cursor, PeekAction action, object state, AsyncCallback callback)
 {
     return _queue.BeginPeek(timeout, cursor, action, state, callback);
 }
Esempio n. 14
0
 private Message PeekMessage(MessageQueue queue, Cursor cursor, PeekAction action)
 {
     try
     {
         return queue.Peek(_timeout, cursor, action);
     }
     catch
     {
         return null;
     }
 }
Esempio n. 15
0
 public Message Peek(TimeSpan timeout, Cursor cursor, PeekAction action)
 {
     CheckDisposed();
     return(_wrapped.Peek(timeout, cursor, action));
 }
Esempio n. 16
0
 private static System.Messaging.Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
 {
     System.Messaging.Message ret = null;
     try
     {
         ret = q.Peek(new TimeSpan(1), cursor, action);
     }
     catch (MessageQueueException mqe)
     {
         //if (!mqe.Message.ToLower().Contains("timeout"))
         if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
         {
             throw;
         }
     }
     return(ret);
 }
Esempio n. 17
0
 /// <summary>
 /// http://jopinblog.wordpress.com/2008/03/12/counting-messages-in-an-msmq-messagequeue-from-c/
 /// </summary>
 /// <param name="cursor"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 protected Message CursorPeekWithoutTimeout( Cursor cursor, PeekAction action)
 {
     Message ret = null;
     try
     {
         ret = _messageQueue.Peek(new TimeSpan(1), cursor, action);
     }
     catch (MessageQueueException mqe)
     {
         if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
         {
             throw;
         }
     }
     return ret;
 }
Esempio n. 18
0
 public IAsyncResult BeginPeek(TimeSpan timeout, Cursor cursor, PeekAction action, object state,
                               AsyncCallback callback)
 {
     CheckDisposed();
     return(_wrapped.BeginPeek(timeout, cursor, action, state, callback));
 }
Esempio n. 19
0
        private Message PeekMessage(MessageQueue queue, Cursor cursor, PeekAction action)
        {
            ResetUnderlyingMessageData();

            try
            {
                underlyingMessageData = queue.Peek(timeout, cursor, action);

                return (Message)underlyingMessageData;
            }
            catch
            {
                return null;
            }
        }
	public Message Peek(System.TimeSpan timeout, Cursor cursor, PeekAction action) {}
Esempio n. 21
0
 /// <summary>
 /// Returns without removing (peeks) the current or next message in the queue, using the specified cursor. The <see cref="M:System.Messaging.MessageQueue.Peek"/> method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.
 /// </summary>
 /// <returns>
 /// A <see cref="T:System.Messaging.Message"/> that represents a message in the queue.
 /// </returns>
 /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that indicates the maximum time to wait for the queue to contain a message. </param><param name="cursor">A <see cref="T:System.Messaging.Cursor"/> that maintains a specific position in the message queue.</param><param name="action">One of the <see cref="T:System.Messaging.PeekAction"/> values. Indicates whether to peek at the current message in the queue, or the next message.</param><exception cref="T:System.ArgumentOutOfRangeException">A value other than PeekAction.Current or PeekAction.Next was specified for the <paramref name="action"/> parameter.</exception><exception cref="T:System.ArgumentNullException">The <paramref name="cursor"/> parameter is null.</exception><exception cref="T:System.ArgumentException">The value specified for the <paramref name="timeout"/> parameter is not valid. Possibly <paramref name="timeout"/> is less than <see cref="F:System.TimeSpan.Zero"/> or greater than <see cref="F:System.Messaging.MessageQueue.InfiniteTimeout"/>. </exception><exception cref="T:System.Messaging.MessageQueueException">An error occurred when accessing a Message Queuing method. </exception>
 public Message Peek(TimeSpan timeout, Cursor cursor, PeekAction action)
 {
     return _queue.Peek(timeout, cursor, action);
 }
Esempio n. 22
0
        /// <summary>
        /// Peek next message from MSMQ by initiating one more BeginPeek call.
        /// </summary>
        private void PeekMessage()
        {
            BrokerTracing.TraceVerbose("[MSMQMessageFetcher] .PeekMessage: one more BeginPeek");

            if (this.isDisposedField)
            {
                BrokerTracing.TraceInfo("[MSMQMessageFetcher] .PeekMessage: the instance is disposed");
                this.RevertFetchCount();
                return;
            }

            List <Exception> exceptions = new List <Exception>();

#if DEBUG
            int peekCount = 0;
#endif
            while (true)
            {
                if (this.pendingFetchCount < 1)
                {
                    break;
                }

                this.rwlockMessagePeekCursorField.EnterUpgradeableReadLock();
                Debug.WriteLine($"[MSMQMessageFetcher] .PeekMessage: before execution pendingFetchCount={this.pendingFetchCount}");



                try
                {
                    while (this.pendingFetchCount > 0)
                    {
                        RefCountedCursor cursorRef;
                        if (this.messagePeekCursorField == null)
                        {
                            BrokerTracing.TraceInfo("[MSMQMessageFetcher] .PeekMessage: cursor for peek message is disposed");
                            this.RevertFetchCount();
                            return;
                        }
                        else
                        {
                            cursorRef = this.messagePeekCursorField.Acquire();
                        }

                        try
                        {
                            this.msmqQueueField.BeginPeek(this.messagePeekTimespanField, cursorRef.MSMQCursor, this.messagePeekActionField, cursorRef, this.PeekMessageComplete);
                            this.messagePeekActionField = PeekAction.Next;
                            Interlocked.Decrement(ref this.pendingFetchCount);
#if DEBUG
                            peekCount++;
#endif
                        }
                        catch (Exception e)
                        {
                            cursorRef.Release();
                            if (this.isDisposedField)
                            {
                                this.RevertFetchCount();
                                // if the queue is closed, do nothing.
                                return;
                            }

                            exceptions.Add(e);
                        }
                    }
                }
                finally
                {
                    this.rwlockMessagePeekCursorField.ExitUpgradeableReadLock();
                }

                // actively check if there is new message waiting to be fetch. If yes, don't wait for next timer triggering.
                this.CheckAndGetMoreMessages();
            }
#if DEBUG
            Debug.WriteLine($"[MSMQMessageFetcher] .PeekMessage: after execution pendingFetchCount={this.pendingFetchCount}, peekCount={peekCount}");
#endif

            foreach (var exception in exceptions)
            {
                BrokerTracing.TraceError(
                    "[MSMQMessageFetcher] .PeekMessage: BeginPeek message from the queue failed, the exception, {0}.",
                    exceptions.ToString());

                this.HandleMessageResult(new MessageResult(null, exception));
            }
        }
        // Modified PeekByCorrelationId that peeks forward for correlation id
        private Message PeekByCorrelationId(string correlationId, TimeSpan timeout, Cursor cursor, PeekAction action)
        {
            string compare = string.Empty;
            if (!string.IsNullOrEmpty(correlationId))
            {
                compare = correlationId;
            }

            Message m = this.queue.Peek(timeout, cursor, action);
            while (m != null)
            {
                if (String.Compare(m.CorrelationId, 0, Utilities.GetEmptyCorrelationIdStr(), 0, m.CorrelationId.Length, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrEmpty(compare))
                    {
                        return m;
                    }
                }
                else
                {
                    if (String.Compare(m.CorrelationId, 0, compare, 0, m.CorrelationId.Length, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return m;
                    }
                }

                // Continue search, peek next message
                m = this.queue.Peek(timeout, cursor, PeekAction.Next);
            }

            return null;
        }
Esempio n. 24
0
        private static Message PeekWithTimeout(MessageQueue q, double timeout, Cursor cursor, PeekAction action)
        {
            Message ret = null;

            try
            {
                ret = q.Peek(TimeSpan.FromMilliseconds(timeout), cursor, action);
            }
            catch (MessageQueueException mqe)
            {
                if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                {
                    throw;
                }
            }
            return(ret);
        }
	public System.IAsyncResult BeginPeek(System.TimeSpan timeout, Cursor cursor, PeekAction action, object state, System.AsyncCallback callback) {}
Esempio n. 26
0
 public Message Peek(System.TimeSpan timeout, Cursor cursor, PeekAction action)
 {
 }
Esempio n. 27
0
 public System.IAsyncResult BeginPeek(System.TimeSpan timeout, Cursor cursor, PeekAction action, object state, System.AsyncCallback callback)
 {
 }
        // This method peeks the fragments by calling the overloaded Peek methods of the System.Messaging API
        private Message PeekFromMsmq(string correlationId, TimeSpan timeout, Cursor cursor, PeekAction action)
        {
            if (correlationId == null)
            {
                this.message = this.queue.Peek(timeout, cursor, action);
            }
            else
            {
                this.message = this.PeekByCorrelationId(correlationId, timeout, cursor, action);
            }

            return this.message;
        }