Exemple #1
0
        /// <summary>
        /// Returns number of journal message's deleted from queue
        /// </summary>
        /// <param name="queueName">System.String : queueName</param>
        /// <returns></returns>
        private int DeleteOldJournalMessage(string queueName)
        {
            int totalCount = 0;

            try
            {
                queueName += ";JOURNAL";
                using (TransactionScope transaction = new TransactionScope())
                {
                    using (MessageQueue queue = new MessageQueue(queueName))
                    {
                        queue.Formatter = new BinaryMessageFormatter();
                        queue.MessageReadPropertyFilter.ArrivedTime = true;
                        using (MessageEnumerator messageReader = queue.GetMessageEnumerator2())
                        {
                            int JournalLogDays = Convert.ToInt32(ConfigurationManager.AppSettings["JournalLogDays"]);
                            while (messageReader.MoveNext())
                            {
                                Message message = messageReader.Current;
                                if (message.ArrivedTime.AddMinutes(JournalLogDays) < DateTime.Now)
                                {
                                    queue.ReceiveById(message.Id);
                                    totalCount++;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(totalCount);
        }
 public Enumerator(Session session, MessageQueue messageQueue,
                   IMessageReader reader)
 {
     this.session         = session;
     this.innerEnumerator = messageQueue.GetMessageEnumerator2();
     this.reader          = reader;
 }
Exemple #3
0
        private void PeekMessages()
        {
            try
            {
                using (MessageEnumerator messagesEnumerator = ordersQueue.GetMessageEnumerator2())
                {
                    while (messagesEnumerator.MoveNext(TimeSpan.FromHours(3)))
                    {
                        var messageInfo = new MessageInfo
                        {
                            Id    = messagesEnumerator.Current.Id,
                            Label = messagesEnumerator.Current.Label
                        };

                        ordersList.Add(messageInfo);
                    }
                }
                MessageBox.Show("No orders in the last 3 hours. Exiting thread",
                                "Course Order Receiver", MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
            catch (MessageQueueException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #4
0
        protected override void ReadAll()
        {
            using (MessageQueue queue = GetQueue())
            {
                using (MessageEnumerator enumerator = queue.GetMessageEnumerator2())
                {
                    enumerator.Reset();

                    // Gather all messages.

                    var messages = new EventMessages();
                    while (enumerator.MoveNext())
                    {
                        if (RemoveWhenReading)
                        {
                            GetEventMessages(messages, enumerator.RemoveCurrent());
                        }
                        else
                        {
                            GetEventMessages(messages, enumerator.Current);
                        }
                    }

                    // Pass all of them on.

                    HandleEventMessages(messages);
                }
            }
        }
Exemple #5
0
        public MessageEnumerator ReceiveAllMessages()
        {
            MessageQueue      queue      = null;
            MessageEnumerator enumerator = null;

            try
            {
                queue = new MessageQueue(_QueueInboxName);

                //retrieve all messages from the queue
                enumerator = (MessageEnumerator)(queue.GetEnumerator());
            }
            catch (Exception exception)
            {
                EventLog systemLog = new EventLog();
                systemLog.Source = "IssueTracker";
                systemLog.WriteEntry(exception.Message, EventLogEntryType.Error, 0);
            }
            finally
            {
                queue.Close();
            }

            return(enumerator);
        }
Exemple #6
0
        // 从 MSMQ 队列中移走若干消息
        // parameters:
        public void RemoveMessage(int nCount)
        {
            if (nCount == 0)
            {
                return;
            }

            List <MessageData> results = new List <MessageData>();
            TimeSpan           timeout = new TimeSpan(0, 0, 1);

            try
            {
                MessageEnumerator iterator = _queue.GetMessageEnumerator2();
                int i = 0;
                while (iterator.MoveNext(timeout))
                {
                    if (i >= nCount)
                    {
                        break;
                    }

                    iterator.RemoveCurrent();
                    i++;
                }
                return;
            }
            catch (MessageQueueException ex)
            {
                this.App.WriteErrorLog("RemoveMessage(" + nCount + ") 出现异常: " + ExceptionUtil.GetDebugText(ex));
            }
            catch (Exception ex)
            {
                this.App.WriteErrorLog("RemoveMessage(" + nCount + ") 出现异常: " + ExceptionUtil.GetDebugText(ex));
            }
        }
Exemple #7
0
        public int GetQueeuElementsCount(string pQueuePach)
        {
            // Holds the count of Lowest priority messages.
            int numberItems = 0;

            // Connect to a queue.
            MessageQueue myQueue = new MessageQueue(pQueuePach);

            // Get a cursor into the messages in the queue.
            MessageEnumerator myEnumerator = myQueue.GetMessageEnumerator();

            // Specify that the messages's priority should be read.
            myQueue.MessageReadPropertyFilter.Priority = true;

            // Move to the next message and examine its priority.
            while (myEnumerator.MoveNext())
            {
                // Increase the count if priority is Lowest.
                if (myEnumerator.Current.Priority == MessagePriority.Lowest)
                {
                    numberItems++;
                }
            }



            return(numberItems);
        }
Exemple #8
0
        public List <MessageModel> GetAllMessageByQueueName(string queuename)
        {
            var list = new List <MessageModel>();

            _ClientQueue.Path = @".\private$\" + queuename;
            MessageEnumerator enumerator    = _ClientQueue.GetMessageEnumerator2();
            List <Message>    queueMessages = new List <Message>();

            while (enumerator.MoveNext(new TimeSpan(0, 0, 1)))
            {
                queueMessages.Add(enumerator.Current);
                Message message = _ClientQueue.ReceiveById(enumerator.Current.Id);
                message.Formatter = new BinaryMessageFormatter();
                try
                {
                    list.Add(new MessageModel {
                        Label = message.Label, Body = message.Body, QueueName = queuename, IsSuccess = true
                    });
                }
                catch (Exception ex)
                {
                    _ClientQueue.Send(message);
                }
            }
            _ClientQueue.Close();

            return(list);
        }
Exemple #9
0
        private Task ProcessMessagesAsync(MessageEnumerator enumerator)
        {
            try
            {
                if (!enumerator.MoveNext(TimeSpan.FromMilliseconds(10)))
                {
                    return(Task.CompletedTask);
                }
            }
            catch (Exception exception)
            {
                Logger.Warn("MSMQ receive operation failed", exception);
                return(Task.CompletedTask);
            }

            if (this.cancellationToken.IsCancellationRequested)
            {
                return(Task.CompletedTask);
            }

            var handlerTask = this.HandleMessageAsync();

            this.handlerTasks.TryAdd(handlerTask, handlerTask);

            return(handlerTask.ContinueWith(t =>
            {
                Task toBeRemoved;
                this.handlerTasks.TryRemove(t, out toBeRemoved);
            }, TaskContinuationOptions.ExecuteSynchronously));
        }
        /// <summary>
        ///
        /// </summary>
        public void StartInputProcessing()
        {
            SystemComponents.MSMQHandler mqHandler = new SystemComponents.MSMQHandler();

            LogCons.Inst.Write(LogLevel.Fatal, "MSMQ is {0}installed", mqHandler.IsMSMQInstalled() == true ? string.Empty:"NOT ");
            LogCons.Inst.Write(LogLevel.Fatal, "MSMQ is {0}running", mqHandler.IsMSMQRunning() == true ? string.Empty : "NOT ");

            if (mqHandler.IsMSMQInstalled() == false)
            {
                mqHandler.Install();
            }

            stopThreads = false;

            try
            {
                this.minaryQueue            = new MessageQueue(_LOCAL_ENDPOINT);
                this.minaryQueueEnumerator  = this.minaryQueue.GetMessageEnumerator2();
                this.processInputDataThread = new Thread(this.DataProcessingThread);
                this.processInputDataThread.Start();
            }
            catch (Exception ex)
            {
                LogCons.Inst.Write(LogLevel.Fatal, $"An error occurred while starting the input processor MessageQueue : {ex.Message}\r\nStacktrace: {ex.StackTrace}");
                var message = $"An error occurred while starting the input processor MessageQueue : {ex.Message}\r\n\r\nStacktrace: {ex.StackTrace}";
                MessageDialog.Inst.ShowError(string.Empty, message, this.minaryMain);
            }
        }
Exemple #11
0
        private static void Main()
        {
            var queue = new MessageQueue(LocalPrivateQueue)
            {
                Formatter = new XmlMessageFormatter(new[]
                {
                    typeof(string)
                })
            };

            // Использование IEnumerable
            foreach (Message message in queue)
            {
                Console.WriteLine(message);
            }

            // Использование перечислителя очереди
            using (MessageEnumerator enumerator = queue.GetMessageEnumerator2())
            {
                while (enumerator.MoveNext(TimeSpan.FromMinutes(30))) // Время на ожидание сообщения
                {
                    Message currentMessage = enumerator.Current;
                    if (currentMessage != null)
                    {
                        Console.WriteLine(currentMessage.Body);
                    }
                }
            }
        }
Exemple #12
0
        //将消息队列中的邮件发送到邮箱中
        private void btnAllSend_Click(object sender, EventArgs e)
        {
            string queuePath = @".\private$\lxfMail";
            //List<MailInfo> listMail = QueueManger.GetAllMessage<MailInfo>(queuePath);
            //foreach (MailInfo mi in listMail)
            //{
            //    //MessageBox.Show(mi.Content);
            //    bool isPass = SendMail(mi);
            //    if (isPass == true)
            //    {
            //    }
            //}

            MessageQueue myQueue = new MessageQueue(queuePath);

            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MailInfo) });
            MessageEnumerator enumerator = myQueue.GetMessageEnumerator2();

            while (enumerator.MoveNext())
            {
                MailInfo mi     = (MailInfo)enumerator.Current.Body;
                bool     isPass = SendMail(mi);
                if (isPass == true)
                {
                    //enumerator.RemoveCurrent();
                    myQueue.ReceiveById(enumerator.Current.Id);
                }
                MessageBox.Show(mi.Content);
            }
        }
Exemple #13
0
        private void PeekMessages()
        {
            try
            {
                using (MessageEnumerator messagesEnumerator = _ordersQueue.GetMessageEnumerator2())
                {
                    while (messagesEnumerator.MoveNext(TimeSpan.FromHours(3)))
                    // NOTE: Если в течение 3-х часов сообщений не было, покидаем цикл
                    {
                        Message currentMessage = messagesEnumerator.Current;
                        if (currentMessage != null)
                        {
                            var messageInfo = new MessageInfo
                            {
                                Id    = currentMessage.Id,
                                Label = currentMessage.Label
                            };

                            _ordersList.Add(messageInfo);
                        }
                    }
                }

                MessageBox.Show("No orders in the last 3 hours. Exiting thread", "Course Order Receiver",
                                MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (MessageQueueException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        //**************************************************
        // Iterates through messages in a queue and examines
        // their priority.
        //**************************************************

        public void CountLowestPriority()
        {
            // Holds the count of Lowest priority messages.
            uint numberItems = 0;

            // Connect to a queue.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            // Get a cursor into the messages in the queue.
            MessageEnumerator myEnumerator =
                myQueue.GetMessageEnumerator();

            // Specify that the messages's priority should be read.
            myQueue.MessageReadPropertyFilter.Priority = true;

            // Move to the next message and examine its priority.
            while (myEnumerator.MoveNext())
            {
                // Increase the count if priority is Lowest.
                if (myEnumerator.Current.Priority ==
                    MessagePriority.Lowest)
                {
                    numberItems++;
                }
            }

            // Display final count.
            Console.WriteLine("Lowest priority messages: " +
                              numberItems.ToString());

            return;
        }
Exemple #15
0
        public GxQueueMessage GetFirst()
        {
            mEof  = false;
            mEnum = mq.GetMessageEnumerator();

            return(GetNext());
        }
        public int ReadQueueSize(string refNum)
        {
            try
            {
                if (MessageQueue.Exists(@".\Private$\ScrapeSessionsQueue"))
                {
                    MessageQueue mQ = new MessageQueue(@".\Private$\ScrapeSessionsQueue", false, true);

                    int messageCount = 0;

                    using (MessageEnumerator messageEnumerator = mQ.GetMessageEnumerator2())
                    {
                        while (messageEnumerator.MoveNext())
                        {
                            messageCount++;
                        }
                    }

                    return(messageCount);
                }

                return(0);
            }
            catch (Exception ex)
            {
                log.LogMessage(Enumeration.LoggingPriority.High, refNum, ex);

                return(0);
            }
        }
 public void Dispose()
 {
     if (innerEnumerator != null)
     {
         innerEnumerator.Close();
         innerEnumerator = null;
     }
 }
Exemple #18
0
 protected virtual void ReceiveMessage(MessageEnumerator enumerator, TimeSpan timeout,
                                       Action <Message> receiveAction)
 {
     using (Message message = enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.None))
     {
         receiveAction(message);
     }
 }
        protected virtual void ReceiveMessage(MessageEnumerator enumerator, TimeSpan timeout, Action <Func <Message> > receiveAction)
        {
            receiveAction(() => enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.None));
            // ADK - End Server PurePath Here
            DynaTraceADKFactory.initialize();
            Tagging adk = DynaTraceADKFactory.createTagging();

            adk.endServerPurePath();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            MessageEnumerator messageEnumerator = base.GetMessageEnumerator2();

            while (messageEnumerator.MoveNext())
            {
                yield return(messageEnumerator.Current);
            }
        }
Exemple #21
0
        private static bool MoveToNextMessage(MessageQueue queue, MessageEnumerator enumerator, bool firstMessage, ref bool current)
        {
            // This function effectively replaces MessageEnumerator.MoveNext(). The problem with that function is
            // that once it reaches the end of the queue it closes the cursor, so the next call to MoveNext()
            // starts from the start again whereas we want to keep trying to retrieve the next message when it
            // arrives.

            // When moving to the very first message call MoveNext() on the enumerator, so that it updates its
            // own internal state. Afterwards manually check for the next message (which will advance the cursor,
            // so there's no need to call MoveNext()). When we reach the end of the queue (IOTimeout is returned) the
            // cursor is positioned PAST the last message, so next time we need to read the CURRENT message, not
            // the next one (current is set to true). Once a new message arrives in the queue read the NEXT
            // message (current is set to false).

            Debug.Assert(queue != null && enumerator != null, "queue != null && enumerator != null");

            if (firstMessage)
            {
                try
                {
                    return(enumerator.MoveNext());
                }
                catch (MessageQueueException ex)
                {
                    if ((uint)ex.MessageQueueErrorCode == 0x80070005)
                    {
                        throw new ApplicationException(string.Format("Access is denied to queue '{0}'."
                                                                     + " Ensure that you have 'Receive Message' permissions for the queue.",
                                                                     queue.FormatName), ex);
                    }

                    throw new ApplicationException(string.Format("Failed to read from queue '{0}'.",
                                                                 queue.FormatName), ex);
                }
            }

            int action = (current ? NativeMethods.MQ_ACTION_PEEK_CURRENT : NativeMethods.MQ_ACTION_PEEK_NEXT);

            int hr = UnsafeNativeMethods.MQReceiveMessage(queue.ReadHandle, 0, action, IntPtr.Zero,
                                                          IntPtr.Zero, IntPtr.Zero, enumerator.CursorHandle, IntPtr.Zero);

            switch (hr)
            {
            case NativeMethods.MQ_OK:
                current = false;
                return(true);

            case (int)MessageQueueErrorCode.IOTimeout:
                current = true;
                return(false);            // No more messages.

            default:
                Debug.WriteLine("MQReceiveMessage returned " + ((MessageQueueErrorCode)hr));
                return(false);
            }
        }
        private int GetMessageCount(MessageQueue m)
        {
            Int32             count   = 0;
            MessageEnumerator msgEnum = m.GetMessageEnumerator2();

            while (msgEnum.MoveNext(new TimeSpan(0, 0, 0)))
            {
                count++;
            }
            return(count);
        }
Exemple #23
0
        /*
         * Function:    GetMessageCount
         *
         * Description:	Gets the amount of messages that are within the message queue
         *
         * Parameters:	MessageQueue m
         *
         * Returns:		void
         */
        private int GetMessageCount(MessageQueue m)
        {
            Int32 count = 0;
            //Increments the counter based on the number of items
            MessageEnumerator msgEnum = m.GetMessageEnumerator2();

            while (msgEnum.MoveNext(new TimeSpan(0, 0, 0)))
            {
                count++;
            }
            return(count);
        }
Exemple #24
0
        private int GetQueueDepth(MessageQueue mq)
        {
            int count = 0;
            MessageEnumerator enumerator = mq.GetMessageEnumerator2();

            while (enumerator.MoveNext())
            {
                count++;
            }

            return(count);
        }
Exemple #25
0
    public string ReceiveMessages(string companyCode, string retailID, string terminalID)
    {
        //WILL REMOVE FROM QUEUE
        string str_foldername = companyCode + "_" + retailID.PadLeft(3, '0') + "_" + terminalID.PadLeft(2, '0') + "_out";
        string queueName      = @".\private$\" + str_foldername;
        string result         = "Finished";

        //Receiving Messages from MSMQ
        MessageQueue messageQueue = new MessageQueue(queueName);

        messageQueue.DefaultPropertiesToSend.Recoverable = true;
        messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

        //To keep a check that if no messages present in MSMQ,
        //control should return back in 1 second.
        TimeSpan timeout = new TimeSpan(5);

        System.Messaging.Message message = null;

        //Get all the messages present in the MSMQ and iterate through it.
        MessageEnumerator enumerator = messageQueue.GetMessageEnumerator2();

        int i = 0;

        while (enumerator.MoveNext(timeout) && i < 100)
        {
            message = enumerator.RemoveCurrent(timeout);
            if (message != null)
            {
                string str_backupfoldername = companyCode + "_" + retailID.PadLeft(3, '0') + "_" + terminalID.PadLeft(2, '0') + "_backup";
                string path_backupqueue     = @".\private$\" + str_backupfoldername;

                createMsmqQueue(path_backupqueue);
                MessageQueue myBackupQueue = new MessageQueue(path_backupqueue);
                myBackupQueue.DefaultPropertiesToSend.Recoverable = true;
                System.Messaging.Message myBackupMessage = new System.Messaging.Message();

                string tablename;
                XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                message.Formatter = formatter;
                string context = message.Body.ToString();
                if (context != null && context.Length > 0)
                {
                    myBackupMessage.Label = "Generate_Server_" + message.Label;
                    myBackupMessage.Body  = message.Body;
                    myBackupQueue.Send(myBackupMessage);
                }
            }
            enumerator.Reset();
            i++;
        }
        return(result);
    }
        protected override void ReceiveMessage(MessageEnumerator enumerator, TimeSpan timeout, Action <Func <Message> > receiveAction)
        {
            receiveAction(() =>
            {
                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Removing message {0} from queue {1}", enumerator.Current.Id, Address);
                }

                return(enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.Automatic));
            });
        }
Exemple #27
0
        public void MQPoller()
        {
            bool msgsent;

            while (true)
            {
                Thread.Sleep(ThePollingInterval);
                try
                {
                    #region traverse the messages in queue and transmit them !
                    qLock = new Object();
                    lock (qLock)
                    {
                        try
                        {
                            MessageQueue queue = new MessageQueue(@".\private$\shadow");
                            if (queue.CanRead) // can we read ?
                            {
                                MessageEnumerator me = queue.GetMessageEnumerator2();
                                me.Reset();
                                while (me.MoveNext()) // flush awayyy.....
                                {
                                    System.Messaging.Message msg = queue.Receive();
                                    msg.Formatter = new BinaryMessageFormatter();
                                    // TRANSMIT
                                    #region traverse clients hashtable and broadcast mq contents to all of them
                                    foreach (int k in htSocketList.Keys)
                                    {
                                        //MessageBox.Show(msg.Body.ToString());
                                        Thread.Sleep(100);
                                        msgsent = SendBytesToClient(ccmd.BroadcastText(msg.Label + "|" + msg.Body, Convert.ToString(k)), ((ServerSocketPacket)htSocketList[k]).m_clientNumber, ((ServerSocketPacket)htSocketList[k]).m_clientId);
                                    }
                                    #endregion
                                }
                            }
                            queue.Close();
                            queue = null;
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show("Error Transmitting:"+ex.Message);
                        }
                    }
                    qLock = null;
                    #endregion
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error Traversing clients:"+ex.Message);
                }
            }
        }
Exemple #28
0
        //获取指定消息队列的长度
        public static int GetQueueLen(string strPath)
        {
            MessageQueue      mq      = new MessageQueue(strPath, false);
            int               iNum    = 0;
            MessageEnumerator msgEnum = mq.GetMessageEnumerator2();

            mq.Close();
            while (msgEnum.MoveNext())
            {
                iNum++;
            }
            return(iNum);
        }
        public IEnumerable <MessageDelivery> ListMessages()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("MsmqMessageDeliveryQueue");
            }

            MessageEnumerator enumerator = _queue.GetMessageEnumerator2();

            while (enumerator.MoveNext())
            {
                yield return(createObject(enumerator.Current));
            }
        }
Exemple #30
0
        public static SqlInt32 CountMessageOnQue(SqlString queueName)
        {
            CreateIfNotExists(queueName.Value);

            MessageQueue      messageQueue      = new MessageQueue(queueName.Value, QueueAccessMode.SendAndReceive);
            MessageEnumerator messageEnumerator = messageQueue.GetMessageEnumerator2();
            int i = 0;

            while (messageEnumerator.MoveNext())
            {
                i++;
            }
            return(new SqlInt32(i));
        }