예제 #1
0
        public void ShouldFailOldMessages()
        {
            var task = new MessageTask
            {
                Category     = goodCategoryA,
                Contact      = contact1,
                DispatchDate = TestDate.AddDays(-1.5), // пропущенная задача
                Status       = MessageTask.TaskStatus.New,
            };

            db.MessageTasks.Add(task);
            db.SaveChanges();

            dispatcher.Dispatch(TestDate);

            db.Entry(task).Reload();

            Assert.Equal(MessageTask.TaskStatus.Pending, task.Status);
            Assert.True(task.LastTryDate > task.DispatchDate);

            Assert.True(vk.HasSent());
        }
        public void Enqueue(MessageTask callback, ConnectionResponse obj)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (!_enqueueAsyncMessages)
            {
                HandleAsyncMessage(callback, obj);
                return;
            }

            // Keep a ref to this task until it completes. If it can't finish by the time we dispose this queue,
            // then we'll find it and cancel it.
            lock (_pendingTasks)
            {
                _pendingTasks.Add(callback);
            }

            var task = Task.Run(() => HandleAsyncMessage(callback, obj));

            // Unhandled error handler
            task.ContinueWith(t =>
            {
                _logger.LogError(t.Exception, "Failed to complete async handling of SendAsync for {callback}", callback.Method);
                callback.TaskWrapper.TrySetException(t.Exception !); // t.Exception is available since this runs only on faulted
            }, TaskContinuationOptions.OnlyOnFaulted);

            // Always remove from the queue when done, regardless of outcome.
            task.ContinueWith(_ =>
            {
                lock (_pendingTasks)
                {
                    _pendingTasks.Remove(callback);
                }
            });
        }
예제 #3
0
        private void HandleTask(MessageTask task, DateTime now)
        {
            if (task.Status == MessageTask.TaskStatus.New && (now - task.DispatchDate).TotalDays >= 1)
            {
                UpdateTask(task, false, "Сообщение не отправлено в запланированную дату");
                return;
            }

            var category = task.Category;
            var contact  = task.Contact;

            try
            {
                IMessageTemplate template = new MessageTemplate(category.Template);

                var requiredFields = template.Fields;
                var user           = VK.GetUser(contact.VKID, requiredFields);

                var messageText = template.Substitute(user);
                VK.SendMessage(contact.VKID, messageText);

                UpdateTask(task, true, "Сообщение успешно отправлено");
            }
            catch (MessageTemplateSyntaxException ex)
            {
                UpdateTask(task, false, "Синтаксическая ошибка в шаблоне", ex);
            }
            catch (VkApiException ex)
            {
                UpdateTask(task, false, "Ошибка соединения с ВКонтакте", ex);
            }
            catch (Exception ex)
            {
                UpdateTask(task, false, "Неизвестная ошибка", ex);
            }
        }
예제 #4
0
 /// <summary>
 /// Sets the finished to task failed.
 /// </summary>
 /// <param name="messagesToAcknowledge">The messages to acknowledge.</param>
 internal void SetFinishedToTaskFailed(Dictionary <long, MessageTask> messagesToAcknowledge)
 {
     for (int i = 0; i < this.mMessageQueues.Count; i++)
     {
         Queue <MessageTask> queue = this.mMessageQueues[i];
         lock (queue)
         {
             while (queue.Count > 0)
             {
                 MessageTask task = queue.Dequeue();
                 lock (messagesToAcknowledge)
                 {
                     // kipucolom a várakozók közül
                     if (messagesToAcknowledge.ContainsKey(task.Message.MessageId))
                     {
                         task.IsSuccess = false;
                         task.RaiseSentEventFinished();
                         messagesToAcknowledge.Remove(task.Message.MessageId);
                     }
                 }
             }
         }
     }
 }
예제 #5
0
 public void updateThreadLastModifiedTime(VerseMessageThread vmt, VerseMessage vm)
 {
     if (vmt != null)
      {
          DateTime datetime = DateTime.Now;
          vmt.datetime_last_modified = datetime;
          MessageTask mt = new MessageTask(us, vm);
          mt.UpdateLastAccessedTime();
      }
 }
        private void OnMessage(string s)
        {
            if ((s != null) && !s.Equals(""))
            {
                Topper mms = new Topper(s);

                string op = mms.op;

                if ("publish".Equals(op))
                {
                    string topic      = mms.topic;
                    string msg_params = "";

                    // if we have message parameters, parse them
                    Match      m   = Regex.Match(s, @"""msg""\s*:\s*({.*}),");
                    ROSMessage msg = null;
                    if (m.Success)
                    {
                        msg_params = m.Groups[1].Value;
                    }

                    foreach (var sub in _subscribers)
                    {
                        // only consider subscribers with a matching topic
                        if (topic != sub.Key.topic)
                        {
                            continue;
                        }

                        msg = sub.Key.ParseMessage(msg_params);
                        MessageTask newTask = new MessageTask(sub.Key, msg);
                        lock (_readLock)
                        {
                            _msgQueue[topic].Enqueue(newTask);
                        }
                    }
                }
                else if (Regex.IsMatch(s, @"""op""\s*:\s*""call_service""")) // op is call_service
                {
                    ServiceHeader hdr = new ServiceHeader(s);
                    foreach (var srv in _serviceServers)
                    {
                        if (srv.Key.topic == hdr.service)
                        {
                            ServiceArgs     args     = null;
                            ServiceResponse response = null;
                            // if we have args, parse them (args are optional on services, though)
                            Match m = Regex.Match(s, @"""args""\s*:\s*({.*}),");
                            if (m.Success)
                            {
                                args = srv.Key.ParseRequest(m.Groups[1].Value);
                            }

                            // add service request to queue, to be processed later in Render()
                            lock (_readLock)
                            {
                                _svcQueue[srv.Key.topic].Enqueue(new ServiceTask(srv.Key, args, hdr.id));
                            }

                            break; // there should only be one server for each service
                        }
                    }
                }
                else
                {
                    Debug.LogWarning("Unhandled message:\n" + s);
                }
            }
            else
            {
                Debug.Log("Got an empty message from the web socket");
            }
        }
        private void OnMessage <Tmsg>(string message) where Tmsg : RosMessage
        {
//			Debug.LogWarning("OnMessage="+message);

            if ((message != null) && !message.Equals(string.Empty))
            {
                Topper topper = new Topper(message);

                if ("publish".Equals(topper.op))                  // Topic
                {
                    RosbridgeJson <Tmsg> rosbridgeJson = null;

                    foreach (var sub in this.subscribers)
                    {
                        // only consider subscribers with a matching topic
                        if (topper.topic != sub.Key.Topic)
                        {
                            continue;
                        }

                        if (rosbridgeJson == null)
                        {
                            rosbridgeJson = new RosbridgeJson <Tmsg>(message);
                        }

                        MessageTask newTask = new MessageTask(sub.Key, rosbridgeJson.msg);

                        lock (this.lockMsgQueue)
                        {
                            this.msgQueue[rosbridgeJson.topic].Enqueue(newTask);
                        }
                    }
                }
                else if ("call_service".Equals(topper.op))                 // Service
                {
                    RosbridgeJson <Tmsg> rosbridgeJson = new RosbridgeJson <Tmsg>(message);

                    foreach (var srv in this.serviceProviders)
                    {
                        if (srv.Key.Name == rosbridgeJson.service)
                        {
                            ServiceArgs args = null;
//							ServiceResponse response = null;

                            // if we have args, parse them (args are optional on services, though)
                            Match match = Regex.Match(message, @"""args""\s*:\s*({.*}),");
                            if (match.Success)
                            {
                                args = srv.Key.ParseRequest(match.Groups[1].Value);
                            }

                            // add service request to queue, to be processed later in Render()
                            lock (this.lockMsgQueue)
                            {
                                this.svcQueue[srv.Key.Name].Enqueue(new ServiceTask(srv.Key, args, rosbridgeJson.id));
                            }

                            break;                             // there should only be one server for each service
                        }
                    }
                }
                else
                {
                    Debug.LogWarning("Unhandled message:\n" + message);
                }
            }
            else
            {
                Debug.Log("Got an empty message from the web socket");
            }
        }
예제 #8
0
        private void Send(object state)
        {
            if (mConnected)
            {
                MessageTask         task          = null;
                Queue <MessageTask> selectedQueue = null;
                foreach (Queue <MessageTask> queue in this.mMessageQueues)
                {
                    lock (queue)
                    {
                        if (queue.Count > 0)
                        {
                            selectedQueue = queue;
                            task          = queue.Peek();
                            break;
                        }
                    }
                }

                if (task != null)
                {
                    Stopwatch watch = Stopwatch.StartNew();
                    try
                    {
                        if (task.Message.MessageCode == MessageCodeEnum.LowLevelTcpAcknowledge)
                        {
                            // alacsonyszintű visszajelzés
                            this.mNetworkStream.Write(LOW_LEVEL_RESPONSE_BYTE, 0, LOW_LEVEL_RESPONSE_BYTE.Length);
                        }
                        else
                        {
                            if (task.Message.MessageType == MessageTypeEnum.Tcp)
                            {
                                // a TCP üzenetekről kérek alacsony szintű visszajelzést
                                lock (mSentTCPMessages)
                                {
                                    mSentTCPMessages.Add(task);
                                }
                            }
                            this.mMessageFormatter.Write(this.mNetworkStream, task.Message);
                        }
                        watch.Stop();
                        if (LOGGER.IsDebugEnabled)
                        {
                            LOGGER.Debug(string.Format("NETWORK_CONNNECTION, Id: {0}, Message sent. MessageId: {1}", this.mNetworkStream.Id.ToString(), task.Message.MessageId.ToString()));
                        }
                        mReplyTime = watch.ElapsedMilliseconds;
                        lock (selectedQueue)
                        {
                            selectedQueue.Dequeue();
                        }
                        // sikeres küldés
                        Raiser.CallDelegatorBySync(MessageSendAfter, new object[] { this, new MessageSendEventArgs(task, false) });
                        lock (LOCK_OBJECT)
                        {
                            mTotalMessagesToSend--;
                            if (mTotalMessagesToSend > 0)
                            {
                                THREADPOOL.QueueUserWorkItem(new WaitCallback(Send));
                            }
                        }
                    }
                    catch (ObjectDisposedException ex)
                    {
                        // hálózati hiba (lezárt stream)
                        if (LOGGER.IsErrorEnabled)
                        {
                            LOGGER.Error(string.Format("Id: {0}, {1}, {2}", mNetworkStream.Id, ex.GetType().Name, ex.Message));
                        }
                        HandleDisconnection();
                    }
                    catch (IOException ex)
                    {
                        // hálózati hiba
                        if (LOGGER.IsErrorEnabled)
                        {
                            LOGGER.Error(string.Format("Id: {0}, {1}, {2}", mNetworkStream.Id, ex.GetType().Name, ex.Message));
                        }
                        this.mNetworkStream.Dispose();
                        HandleDisconnection();
                    }
                    catch (InvalidOperationException ex)
                    {
                        // hálózati hiba
                        if (LOGGER.IsErrorEnabled)
                        {
                            LOGGER.Error(string.Format("Id: {0}, {1}, {2}", mNetworkStream.Id, ex.GetType().Name, ex.Message));
                        }
                        this.mNetworkStream.Dispose();
                        HandleDisconnection();
                    }
                    catch (Exception ex)
                    {
                        // ismeretlen hiba
                        if (LOGGER.IsErrorEnabled)
                        {
                            LOGGER.Error(string.Format("Id: {0}, {1}, {2}", mNetworkStream.Id, ex.GetType().Name, ex.Message));
                        }
                        lock (selectedQueue)
                        {
                            selectedQueue.Dequeue();
                        }
                        this.mNetworkStream.Dispose();
                        HandleDisconnection();
                    }
                    finally
                    {
                        if (watch.IsRunning)
                        {
                            watch.Stop();
                        }
                    }
                }
            }
        }
예제 #9
0
 public MessageDispatcherEventArgs(MessageTask task, MessageDispatcherException exception = null)
 {
     this.Task = task;
     Exception = exception;
 }
        private void OnMessage(string message)
        {
            if ((message != null) && !message.Equals(string.Empty))
            {
                Topper topper = new Topper(message);

                string op = topper.op;

                if ("publish".Equals(op))                  // Topic
                {
                    string topic     = topper.topic;
                    string msgParams = string.Empty;

                    // if we have message parameters, parse them
                    Match      match = Regex.Match(message, @"""msg""\s*:\s*({.*}),");
                    RosMessage msg   = null;

                    if (match.Success)
                    {
                        msgParams = match.Groups[1].Value;
                    }

                    foreach (var sub in this.subscribers)
                    {
                        // only consider subscribers with a matching topic
                        if (topic != sub.Key.Topic)
                        {
                            continue;
                        }

                        msg = sub.Key.ParseMessage(msgParams);
                        MessageTask newTask = new MessageTask(sub.Key, msg);

                        lock (this.lockMsgQueue)
                        {
                            this.msgQueue[topic].Enqueue(newTask);
                        }
                    }
                }
                else if (Regex.IsMatch(message, @"""op""\s*:\s*""call_service"""))                 // Service
                {
                    ServiceHeader header = new ServiceHeader(message);

                    foreach (var srv in this.serviceProviders)
                    {
                        if (srv.Key.Name == header.service)
                        {
                            ServiceArgs args = null;
//							ServiceResponse response = null;

                            // if we have args, parse them (args are optional on services, though)
                            Match match = Regex.Match(message, @"""args""\s*:\s*({.*}),");
                            if (match.Success)
                            {
                                args = srv.Key.ParseRequest(match.Groups[1].Value);
                            }

                            // add service request to queue, to be processed later in Render()
                            lock (this.lockMsgQueue)
                            {
                                this.svcQueue[srv.Key.Name].Enqueue(new ServiceTask(srv.Key, args, header.id));
                            }

                            break;                             // there should only be one server for each service
                        }
                    }
                }
                else
                {
                    Debug.LogWarning("Unhandled message:\n" + message);
                }
            }
            else
            {
                Debug.Log("Got an empty message from the web socket");
            }
        }