Beispiel #1
0
        public static Message TransactionalRemoveCurrent(this MessageEnumerator self)
        {
            if (Transaction.Current != null)
            {
                return(self.RemoveCurrent(MessageQueueTransactionType.Automatic));
            }
            var mqt = MsmqTransactionStrategy.Current;

            if (mqt != null)
            {
                return(self.RemoveCurrent(mqt));
            }

            return(self.RemoveCurrent(MessageQueueTransactionType.Single));
        }
Beispiel #2
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);
                }
            }
        }
Beispiel #3
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));
            }
        }
Beispiel #4
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();
        }
Beispiel #6
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));
            });
        }
Beispiel #8
0
        public object[] PickMessage(string fromQueue)
        {
            using (var queue = new MessageQueue(fromQueue))
            {
                using (MessageEnumerator messageEnumerator2 = queue.GetMessageEnumerator2())
                {
                    if (!messageEnumerator2.MoveNext())
                    {
                        return(null);
                    }

                    Message current = messageEnumerator2.Current;
                    messageEnumerator2.RemoveCurrent();

                    return(DeserializeMessage(current));
                }
            }
        }
        protected override void ReceiveMessage(MessageEnumerator enumerator, TimeSpan timeout,
                                               Action <Message> receiveAction)
        {
            var options = new TransactionOptions
            {
                IsolationLevel = _isolationLevel,
                Timeout        = _transactionTimeout,
            };

            using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                using (Message message = enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.Automatic))
                {
                    receiveAction(message);
                }

                scope.Complete();
            }
        }
Beispiel #10
0
        public void Ids()
        {
            Message once;
            Message twice;

            using (MessageEnumerator enumerator = _queue.GetMessageEnumerator2())
            {
                if (enumerator.MoveNext())
                {
                    once = enumerator.Current;
                    enumerator.MoveNext();
                    twice = enumerator.RemoveCurrent();

                    Assert.AreNotSame(once.Id, twice.Id);
                    var b = twice.BodyType;
                }
                enumerator.Close();
            }
        }
Beispiel #11
0
        public List <string> GetMessage()
        {
            try
            {
                MessageQueue myQueue = new MessageQueue(Path);
                myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                MessageEnumerator me   = myQueue.GetMessageEnumerator2();
                string            msg  = string.Empty;
                List <string>     msgs = new List <string>();
                while (me.MoveNext())
                {
                    msg = me.RemoveCurrent().Body.ToString();
                    msgs.Add(msg);
                }

                return(msgs);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #12
0
        public void The_enumerator_should_skip_over_messages_that_are_being_processed()
        {
            TimeSpan timeout = 10.Seconds();

            using (MessageEnumerator enumerator = _queue.GetMessageEnumerator2())
            {
                while (enumerator.MoveNext(timeout))
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        Message received = enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.Automatic);

                        Assert.IsNotNull(received);

                        Assert.AreEqual(received.Label, _firstMsg.Label);

                        using (MessageEnumerator enumerator2 = _queue.GetMessageEnumerator2())
                        {
                            while (enumerator2.MoveNext(timeout))
                            {
                                using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew))
                                {
                                    Message received2 = enumerator2.RemoveCurrent(timeout, MessageQueueTransactionType.Automatic);

                                    Assert.IsNotNull(received2);

                                    Assert.AreEqual(received2.Label, _secondMsg.Label);

                                    scope2.Complete();
                                }
                            }
                        }

                        scope.Complete();
                    }
                }
            }
        }
Beispiel #13
0
        public void RemoveMessageWithTimeout()
        {
            SendMessage("message 1");
            SendMessage("message 2");
            SendMessage("message 3");
            SendMessage("message 4");

            MessageQueue      mq0 = MQUtil.GetQueue(qName);
            MessageEnumerator me0 = mq0.GetMessageEnumerator();

            TimeSpan ts = new TimeSpan(0, 0, 2);

            me0.MoveNext(ts);
            me0.MoveNext(ts);
            me0.MoveNext(ts);

            Message m0 = me0.RemoveCurrent(ts);

            me0.MoveNext(ts);

            me0.Dispose();
            mq0.Dispose();

            MessageQueue      mq1 = MQUtil.GetQueue(qName);
            MessageEnumerator me1 = mq1.GetMessageEnumerator();

            me1.MoveNext(ts);
            me1.MoveNext(ts);
            me1.MoveNext(ts);

            Message m1 = me1.Current;

            m1.Formatter = new BinaryMessageFormatter();
            Assert.AreEqual("message 4", (String)m1.Body, "body incorrect");

            mq1.Purge();
            MessageQueue.Delete(qName);
        }
Beispiel #14
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                var path = $"{jsonFolder}\\statis.json";
                // 统计数据json读成对象,计算后再json写回源文件
                List <UserBehaviorStatis> statis = JsonConvert.DeserializeObject <List <UserBehaviorStatis> >(File.ReadAllText(path, Encoding.UTF8));

                // Get a cursor into the messages in the queue.
                MessageEnumerator myEnumerator = mq.GetMessageEnumerator2();
                // Specify that the messages's priority should be read.
                mq.MessageReadPropertyFilter.Priority = true;

                while (myEnumerator.MoveNext())
                {
                    Message msg = myEnumerator.Current;
                    msg.Formatter = formatter;
                    string str = msg.Body.ToString();
                    File.AppendAllText($"{jsonFolder}\\mq.txt", str + "\r\n", Encoding.UTF8);
                    mqType type = (mqType)Enum.Parse(typeof(mqType), str.Substring(0, 1));
                    string body = str.Substring(2);
                    statis.Find(s => s.Type == type).Count++;
                    myEnumerator.RemoveCurrent();
                    myEnumerator.Reset();
                }

                File.WriteAllText(path, JsonConvert.SerializeObject(statis));
            }
            catch (Exception ex)
            {
                File.AppendAllText($"{jsonFolder}\\log.txt", ex.Message + "\r\n", Encoding.UTF8);
            }
            finally
            {
                File.AppendAllText($"{jsonFolder}\\log.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "执行完毕\r\n", Encoding.UTF8);
            }
        }
Beispiel #15
0
        public GxQueueMessage GetNext()
        {
            GxQueueMessage gxm          = new GxQueueMessage();
            bool           messageExist = false;
            bool           validMessage = false;

            while (!validMessage)
            {
                try
                {
                    messageExist = mEnum.MoveNext();
                    if (messageExist)
                    {
                        Message m = (Message)(mEnum.Current);
                        gxm.SetBaseMessage(m);
                        validMessage = testMessage(gxm);
                        if (validMessage && !browse)
                        {
                            mEnum.RemoveCurrent();
                        }
                    }
                    else
                    {
                        validMessage = true;
                    }
                }
                catch (MessageQueueException mex)
                {
                    errCode        = 1;
                    errDescription = mex.Message;
                    messageExist   = false;
                    validMessage   = true;
                }
            }
            mEof = !messageExist;
            return(gxm);
        }
Beispiel #16
0
        //[Test]
        // Not supported with AMQP
        public void RemoveMessageWithTx()
        {
            MessageQueue q = MQUtil.GetQueue(qName);

            q.Formatter = new BinaryMessageFormatter();
            q.Send("foo1");
            q.Send("foo2");

            MessageEnumerator       me1 = q.GetMessageEnumerator();
            MessageQueueTransaction tx  = new MessageQueueTransaction();

            me1.MoveNext();
            Message m1 = me1.Current;

            me1.RemoveCurrent(tx);
            tx.Commit();
            me1.Close();

            MessageEnumerator me2 = q.GetMessageEnumerator();

            Assert.IsTrue(me1.MoveNext());
            me2.RemoveCurrent();
            Assert.IsFalse(me2.MoveNext());
        }
 protected virtual void ReceiveMessage(MessageEnumerator enumerator, TimeSpan timeout, Action <Func <Message> > receiveAction)
 {
     receiveAction(() => enumerator.RemoveCurrent(timeout, MessageQueueTransactionType.None));
 }
Beispiel #18
0
        public void Notify()
        {
            // TODO: 要增加判断,防止过分频繁地被调用
            this.MessageConnection.CleanWebDataTable();

            if (this.dp2library.DefaultQueue == "!api")
            {
                try
                {
                    if (this.MessageConnection.ConnectState != Microsoft.AspNet.SignalR.Client.ConnectionState.Connected)
                    {
                        return;
                    }

                    MessageData[] messages = null;
                    string        strError = "";
                    int           nRet     = this.MessageConnection.GetMsmqMessage(
                        out messages,
                        out strError);
                    if (nRet == -1)
                    {
                        this.WriteErrorLog("Instance.Notify() 中 GetMsmqMessage() 出错: " + strError);
                        return;
                    }
                    if (messages != null)
                    {
                        foreach (MessageData data in messages)
                        {
                            MessageRecord record = new MessageRecord();
                            record.groups = new string[1] {
                                "gn:_patronNotify"
                            };                                                     // gn 表示 group name
                            record.data   = (string)data.strBody;
                            record.format = "xml";
                            List <MessageRecord> records = new List <MessageRecord> {
                                record
                            };

                            DigitalPlatform.Message.SetMessageRequest param =
                                new DigitalPlatform.Message.SetMessageRequest("create",
                                                                              "dontNotifyMe",
                                                                              records);
                            SetMessageResult result = this.MessageConnection.SetMessageTaskAsync(param,
                                                                                                 _cancel.Token).Result;
                            if (result.Value == -1)
                            {
                                this.WriteErrorLog("Instance.Notify() 中 SetMessageAsync() 出错: " + result.ErrorInfo);
                                return;
                            }
                        }

                        nRet = this.MessageConnection.RemoveMsmqMessage(
                            messages.Length,
                            out strError);
                        if (nRet == -1)
                        {
                            this.WriteErrorLog("Instance.Notify() 中 RemoveMsmqMessage() 出错: " + strError);
                            return;
                        }
                    }

                    this._notifyThread.Activate();
                    return;
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    this.WriteErrorLog("Instance.Notify() 出现异常1: " + ExceptionUtil.GetDebugText(ex));
                }
            }

            // 如果第一次初始化 Queue 没有成功,这里再试探初始化
            InitialQueue(false);

            // 进行通知处理
            if (_queue != null &&
                this.MessageConnection.ConnectState == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected)
            {
                try
                {
                    ServerInfo._recordLocks.LockForWrite(this._queue.Path);
                }
                catch (ApplicationException)
                {
                    // 超时了
                    return;
                }

                bool bSucceed = false;
                try
                {
                    MessageEnumerator iterator = _queue.GetMessageEnumerator2();
                    while (iterator.MoveNext())
                    {
                        Message message = iterator.Current;

                        MessageRecord record = new MessageRecord();
                        record.groups = new string[1] {
                            "gn:_patronNotify"
                        };                                                     // gn 表示 group name
                        record.data   = (string)message.Body;
                        record.format = "xml";
                        List <MessageRecord> records = new List <MessageRecord> {
                            record
                        };

                        int length = record.data.Length;

                        DigitalPlatform.Message.SetMessageRequest param =
                            new DigitalPlatform.Message.SetMessageRequest("create",
                                                                          "dontNotifyMe",
                                                                          records);
                        SetMessageResult result = this.MessageConnection.SetMessageTaskAsync(param,
                                                                                             _cancel.Token).Result;
                        if (result.Value == -1)
                        {
                            this.WriteErrorLog("Instance.Notify() 中 SetMessageAsync() 出错: " + result.ErrorInfo);
                            if (result.String == "_connectionNotFound")
                            {
                                Task.Run(() => TryResetConnection(/*result.String*/));
                            }
                            return;
                        }

                        // http://stackoverflow.com/questions/21864043/with-messageenumerator-removecurrent-how-do-i-know-if-i-am-at-end-of-queue
                        try
                        {
                            iterator.RemoveCurrent();
                        }
                        finally
                        {
                            iterator.Reset();
                        }
                    }

                    bSucceed = true;
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (MessageQueueException ex)
                {
                    // 记入错误日志
                    // Program.WriteWindowsLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    this.WriteErrorLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    // Thread.Sleep(5 * 1000);   // 拖延 5 秒
                }
                catch (InvalidCastException ex)
                {
                    // 记入错误日志
                    // Program.WriteWindowsLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    this.WriteErrorLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    // Thread.Sleep(5 * 1000);   // 拖延 5 秒
                }
                catch (Exception ex)
                {
                    // 记入错误日志
                    // Program.WriteWindowsLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    this.WriteErrorLog("Instance.Notify() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                    // Thread.Sleep(5 * 1000);   // 拖延 5 秒
                }
                finally
                {
                    ServerInfo._recordLocks.UnlockForWrite(this._queue.Path);

                    // 只有当发送到 dp2mserver 成功的情况下才立即重新监控最新 MQ
                    // 否则就等下一轮 Worker() 来处理
                    if (bSucceed == true)
                    {
                        // _queue.BeginPeek(new TimeSpan(0, 1, 0), null, OnMessageAdded);
                        BeginPeek();
                    }
                }
            }
        }