Beispiel #1
0
        void SendMessage(string strGroupName, string strText)
        {
            this.EnableControls(false);

            List <MessageRecord> messages = new List <MessageRecord>();
            MessageRecord        record   = new MessageRecord();

            record.groups = new string [1] {
                strGroupName
            };
            record.data = strText;
            messages.Add(record);

            SetMessageRequest param = new SetMessageRequest("create",
                                                            "",
                                                            messages);

            SetMessageResult result = Program.MainForm.MessageHub.SetMessageAsync(param).Result;

            if (result.Value == -1)
            {
                this.Invoke((Action)(() => MessageBox.Show(this, result.ErrorInfo)));
            }
            else
            {
                // 调用成功后才把输入的文字清除
                this.Invoke((Action)(() => this.textBox_input.Text = ""
                                     ));
            }

            this.EnableControls(true);
        }
Beispiel #2
0
        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="records"></param>
        /// <param name="strGroupName"></param>
        /// <returns>
        /// true    成功
        /// false   失败
        /// </returns>
        bool DeleteMessage(List <MessageRecord> records)
        {
            List <MessageRecord> delete_records = new List <MessageRecord>();

            foreach (MessageRecord source in records)
            {
                MessageRecord record = new MessageRecord();
                // 2016-6-20 jane 不需要传group参数
                record.groups = dp2WeiXinService.C_Group_PatronNotity.Split(new char[] { ',' });
                record.id     = source.id;
                delete_records.Add(record);
            }

            string strError = "";

            // CancellationToken cancel_token = new CancellationToken();

            try
            {
                MessageConnection connection = this.Channels.GetConnectionTaskAsync(
                    this.Url,
                    dp2WeiXinService.C_ConnName_TraceMessage).Result;

                SetMessageRequest param = new SetMessageRequest("expire",
                                                                "dontNotifyMe",
                                                                delete_records);//records);这里应该用delete_records吧,用records好像也没错
                CancellationToken cancel_token = new CancellationToken();
                SetMessageResult  result       = connection.SetMessageTaskAsync(param,
                                                                                new TimeSpan(0, 1, 0),
                                                                                cancel_token).Result;
                if (result.Value == -1)
                {
                    strError = result.ErrorInfo;
                    goto ERROR1;
                }
            }
            catch (AggregateException ex)
            {
                strError = MessageConnection.GetExceptionText(ex);
                goto ERROR1;
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                goto ERROR1;
            }
            return(true);


ERROR1:
            dp2WeiXinService.Instance.WriteErrorLog("DeleteMessage() error : " + strError);

            //this.WriteLog("DeleteMessage() error : " + strError, dp2WeiXinService.C_LogLevel_1);
            return(false);
        }
Beispiel #3
0
        // return:
        //      false   出错
        //      true    成功
        bool SendMessage(
            MessageConnection connection,
            string strGroupName,
            string[] texts)
        {
            string strError = "";

            List <MessageRecord> records = new List <MessageRecord>();

            foreach (string text in texts)
            {
                MessageRecord record = new MessageRecord();
                record.groups     = strGroupName.Split(new char[] { ',' });
                record.creator    = ""; // 服务器会自己填写
                record.data       = text;
                record.format     = "text";
                record.type       = "message";
                record.thread     = "";
                record.expireTime = new DateTime(0);    // 表示永远不失效
                records.Add(record);
            }

            try
            {
                SetMessageRequest param = new SetMessageRequest("create",
                                                                "",
                                                                records);
                SetMessageResult result = connection.SetMessageTaskAsync(param, new CancellationToken()).Result;

                if (result.Value == -1)
                {
                    strError = result.ErrorInfo;
                    goto ERROR1;
                }

                return(true);
            }
            catch (AggregateException ex)
            {
                strError = MessageConnection.GetExceptionText(ex);
                goto ERROR1;
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                goto ERROR1;
            }

ERROR1:
            this.Invoke((Action)(() => MessageBox.Show(this, strError)));
            return(false);
        }
Beispiel #4
0
        // 发送心跳消息给 dp2mserver

        /*
         * <root>
         * <type>patronNotify</type>
         * <recipient>R0000001@LUID:62637a12-1965-4876-af3a-fc1d3009af8a</recipient>
         * <mime>xml</mime>
         * <body>...</body>
         * </root>
         *
         * */
        public bool SendHeartBeat()
        {
            if (this.MessageConnection == null || this.MessageConnection.ConnectState != Microsoft.AspNet.SignalR.Client.ConnectionState.Connected)
            {
                return(false);
            }

            try
            {
                XmlDocument dom = new XmlDocument();
                dom.LoadXml("<root><type>heartbeat</type></root>");
                MessageRecord record = new MessageRecord();
                record.groups = new string[1] {
                    "gn:_patronNotify"
                };                                                     // gn 表示 group name
                record.data   = dom.DocumentElement.OuterXml;
                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.SendHeartBeat() 中 SetMessageAsync() [heartbeat] 出错: " + result.ErrorInfo);
                    if (result.String == "_connectionNotFound")
                    {
                        Task.Run(() => TryResetConnection(/*result.String*/));
                    }
                    return(false);
                }

                return(true);
            }
            catch (ThreadAbortException)
            {
                return(false);
            }
            catch (Exception ex)
            {
                this.WriteErrorLog("Instance.SendHeartBeat() 出现异常: " + ExceptionUtil.GetDebugText(ex));
                return(false);
            }
        }
Beispiel #5
0
        void DeleteMessage(List <MessageRecord> records,
                           string strGroupName)
        {
            List <MessageRecord> delete_records = new List <MessageRecord>();

            foreach (MessageRecord source in records)
            {
                MessageRecord record = new MessageRecord();
                record.groups = strGroupName.Split(new char[] { ',' });
                record.id     = source.id;
                delete_records.Add(record);
            }

            string strError = "";

            // CancellationToken cancel_token = new CancellationToken();

            try
            {
                MessageConnection connection = this.Channels.GetConnectionTaskAsync(
                    this.Url,
                    "").Result;
                SetMessageRequest param = new SetMessageRequest("expire",
                                                                "dontNotifyMe",
                                                                records);

                SetMessageResult result = connection.SetMessageTaskAsync(param, new CancellationToken()).Result;
                if (result.Value == -1)
                {
                    goto ERROR1;
                }
            }
            catch (AggregateException ex)
            {
                strError = MessageConnection.GetExceptionText(ex);
                goto ERROR1;
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                goto ERROR1;
            }
            return;

ERROR1:
            WriteErrorLog("DeleteMessage() error : " + strError);
        }
Beispiel #6
0
        // 对于 .data 超过 chunk_size 的情况可以自动切割为多次发送请求
        public async Task <SetMessageResult> SetMessageAsyncLite(
            SetMessageRequest request)
        {
            // 请求结构中如果具备了 TaskID 值,说明调主想自己控制拼接过程,那这里就直接发送出去
            if (string.IsNullOrEmpty(request.TaskID) == false)
            {
                return(await TrySetMessageAsync(request).ConfigureAwait(false));
            }

            int chunk_size = 4096;
            int length     = GetLength(request);

            if (length < chunk_size)
            {
                return(await TrySetMessageAsync(request));
            }

            SetMessageResult result = null;

            foreach (MessageRecord record in request.Records)
            {
                string taskID = Guid.NewGuid().ToString();
                string data   = record.data;
                int    send   = 0;
                for (; ;)
                {
                    SetMessageRequest current_request = new SetMessageRequest();
                    current_request.TaskID  = taskID;
                    current_request.Style   = request.Style;
                    current_request.Action  = request.Action;
                    current_request.Records = new List <MessageRecord>();
                    MessageRecord current_record = new MessageRecord();
                    // TODO: 除了第一次请求外,其它的都只要 .data 成员具备即可
                    current_record.CopyFrom(record);
                    current_record.data = data.Substring(send, Math.Min(chunk_size, data.Length - send));
                    current_request.Records.Add(current_record);
                    // 这一次就是最后一次
                    if (send + current_record.data.Length >= data.Length)
                    {
                        MessageRecord tail_record = new MessageRecord();
                        tail_record.data = null;    // 表示结束
                        current_request.Records.Add(tail_record);
                    }

                    // TODO:
#if NO
                    result = await HubProxy.Invoke <SetMessageResult>(
                        "SetMessage",
                        current_request);
#endif
                    result = await TrySetMessageAsync(current_request).ConfigureAwait(false);

                    if (result.Value == -1)
                    {
                        return(result);  // 中途出错了
                    }
                    send += current_record.data.Length;
                    if (send >= data.Length)
                    {
                        break;
                    }
                }
            }

            return(result);  // 返回最后一次请求的 result 值
        }
Beispiel #7
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();
                    }
                }
            }
        }