Пример #1
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);
                }
            }
        }
Пример #2
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);
    }
Пример #3
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);
                }
            }
        }
Пример #4
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);
            }
        }
Пример #5
0
        private void PeekRead()
        {
            using (MessageQueue queue = GetQueue())
            {
                using (MessageEnumerator enumerator = queue.GetMessageEnumerator2())
                {
                    // Initialise.

                    enumerator.Reset();
                    bool firstMessage = true;
                    bool current      = false;

                    // When starting try to read all messages on the queue.

                    bool moreToRead = ReadMessages(queue, enumerator, ref firstMessage, ref current);

                    // Continue reading messages until Stop() is called.

                    var readHandles  = new[] { StopEvent, PauseEvent };
                    var pauseHandles = new[] { StopEvent, ContinueEvent };

                    bool stopping = false;
                    while (!stopping)
                    {
                        int timeToWait = (moreToRead ? 0 : Constants.MessageComponents.Msmq.TimeToWaitForNewMessages);
                        switch (WaitHandle.WaitAny(readHandles, timeToWait, false))
                        {
                        case 0:

                            // Stopping, so exit the loop.

                            stopping = true;
                            break;

                        case 1:

                            // Paused, wait for it to start again.

                            switch (WaitHandle.WaitAny(pauseHandles))
                            {
                            case 0:

                                // Stopping, so exit the loop.

                                stopping = true;
                                break;

                            case 1:

                                // Continuing, read whatever messages may have been added.

                                moreToRead = ReadMessages(queue, enumerator, ref firstMessage, ref current);
                                break;
                            }

                            break;

                        case WaitHandle.WaitTimeout:

                            // Read the messages.

                            moreToRead = ReadMessages(queue, enumerator, ref firstMessage, ref current);
                            break;
                        }
                    }
                }
            }
        }
Пример #6
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();
                    }
                }
            }
        }