public void RabbitMq_EnqueueDirectWithProperties()
        {
            var publisherSettings = GetConfig("publisher");
            var consumerSettings  = GetConfig("subscriber");

            // check if config exists
            Assert.NotNull(publisherSettings);
            Assert.NotNull(consumerSettings);

            IQueue queue = new RbmqQueue(new NullLoggerFactory(), publisherSettings, consumerSettings);


            queue.Clear();

            var msg = new QMessage();

            msg.Body = new { Id = 1000, Name = "blabla" };

            msg.Properties = new QProperties()
            {
                CorrelationId = Guid.NewGuid().ToString(),
                ReplyTo       = "me"
            };

            queue.Enqueue(msg);

            var queueuMsg = queue.Dequeue <DummyObject>();

            Assert.NotNull(queueuMsg);
            Assert.True(msg.Properties.CorrelationId == queueuMsg.Properties.CorrelationId);
            Assert.True(msg.Properties.ReplyTo == queueuMsg.Properties.ReplyTo);

            queue.Cleanup();
        }
        public void RabbitMq_CleanupTest()
        {
            var publisherSettings = GetConfig("publisherFanout");
            var consumerSettings  = GetConfig("subscriberFanout");

            // check if config exists
            Assert.NotNull(publisherSettings);
            Assert.NotNull(consumerSettings);

            IQueue queue = new RbmqQueue(new NullLoggerFactory(), publisherSettings, consumerSettings);

            var msg = new QMessage();
            var o   = new DummyObject()
            {
                Id = 1000, Name = "blalbal"
            };

            msg.Body = o;
            queue.Clear();
            queue.Enqueue(msg);
            Thread.Sleep(3000);
            var a = queue.Dequeue <QMessage>();

            Assert.NotNull(a);
            var body = JsonConvert.DeserializeObject <DummyObject>(a.Body.ToString());

            Assert.True(body.Id == 1000);
            var ex = Assert.Catch(() => queue.Cleanup());

            Assert.Null(ex);
        }
Exemplo n.º 3
0
        public static void OnMessage(MessageSource src, QMessage msg)
        {
            try
            {
                QMessage newMsg = msg;

                bool release = MiddlewareCore.OnMessage(ref src, ref newMsg);
                if (release)
                {
                    int stat = ModuleCore.OnMessage(src, newMsg);
                    ServiceCore.OnMessage(src, newMsg, msg, stat != -1, stat >= 0 ? ModuleCore.Modules[stat] : null);
                }
            }
            catch (Exception e)
            {
                StringBuilder sb = new(DateTime.Now.ToString());

                sb.Append($"\nMessage: ");
                if (src.IsGroup)
                {
                    sb.Append($"[{src.group!.ID}] ");
                }
                sb.Append($"[{src.user.ID}] ");
                sb.Append(msg);

                sb.Append($"\n{e}");

                if (BotReg.GetBool("CORE/LOG_ERROR", true) && BotAuth.HasOwner)
                {
                    _ = BotAPI.SendPrivateMessageAsync(BotAuth.Owner, new PlainMessage(sb.ToString()));
                }
                sb.Append("\n\n");
                File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "/log_error.txt", sb.ToString());
            }
        }
        public async Task Enqueue(QMessage msg)
        {
            var jsonified = _serializer.Serialize(msg);

            var messageBuffer = Encoding.UTF8.GetBytes(jsonified);
            await _client.SendAsync(new Message(messageBuffer));
        }
        public async Task DequeueTest()
        {
            // define
            IQueueConsumer consumer = new AzureSBTopicConsumer(new LoggerFactory(), _configuration, new DefaultJsonSerializer(), "subscriber");

            // dequeue
            // TODO
            AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
            QMessage       recievedMsg     = null;
            QProperties    oProperties     = null;

            consumer.MessageRecieved += (m, o) =>
            {
                consumer.Unsubscribe();
                recievedMsg = o;
                oProperties = o.Properties;
                _autoResetEvent.Set();
            };

            consumer.Subscribe();


            Assert.True(_autoResetEvent.WaitOne(3000));
            Assert.NotNull(recievedMsg);
        }
        public void RabbitMq_EnqueueDirectTest()
        {
            var publisherSettings = GetConfig("publisher");
            var consumerSettings  = GetConfig("subscriber");

            // check if config exists
            Assert.NotNull(publisherSettings);
            Assert.NotNull(consumerSettings);

            IQueue queue = new RbmqQueue(new NullLoggerFactory(), publisherSettings, consumerSettings);

            queue.Clear();

            var msg = new QMessage();
            var o   = new DummyObject()
            {
                Id = 1000, Name = "blalbal"
            };

            msg.Body = o;

            queue.Enqueue(msg);

            var queueuMsg = queue.Dequeue <DummyObject>();

            Assert.NotNull(queueuMsg);

            queue.Cleanup();
        }
Exemplo n.º 7
0
        void QReader_QReadEvents(object sender, ReceiveCompletedEventArgs e)
        {
            QMessage _qmessage = e.Message.Body as QMessage;

            QClient _client  = new QClient(_qmessage);
            string  _command = _qmessage.Command.ToLower();

            string _message = _qmessage.Message;

            if (_qmessage.UsePackage == true)
            {
                _message = Serialization.SNG.ReadPackage <string>(_qmessage.Package);
            }

            if (Environment.UserInteractive == true)
            {
                if (e.Message.Label != "CFG")
                {
                    ISigner.WriteDebug(String.Format("READ: '{0}', {1}, {2}, {3}, {4}, {5}, {6}", e.Message.Label, _qmessage.Command, _qmessage.ProductId, _qmessage.pVersion, _qmessage.IpAddress, _qmessage.HostName, _message));
                }
                else
                {
                    var    _dbps        = _qmessage.Package.ToParameters();
                    string _companyId   = _dbps["companyId"].ToString();
                    string _corporateId = _dbps["corporateId"].ToString();
                    string _productId   = _dbps["productId"].ToString();
                    string _pVersion    = _dbps["pVersion"].ToString();
                    string _appkey      = _dbps["appkey"].ToString();
                    string _appvalue    = _dbps["appValue"].ToString();

                    ISigner.WriteDebug(String.Format("READ: '{0}', {1}, {2}, {3}, {4}, {5}, {6}", e.Message.Label, _companyId, _corporateId, _productId, _pVersion, _appkey, _appvalue));
                }
            }

            if (e.Message.Label == "CMD")         // command
            {
                string _product = _qmessage.ProductId;

                if (_product != ISigner.Manager.ProductId)
                {
                    if (_command == "pong")
                    {
                        QWriter.SetPingFlag(new QClient(_qmessage));
                    }
                    else if (_command == "signin")
                    {
                        QWriter.AddAgency(ISigner.Manager, _qmessage);
                    }
                    else if (_command == "signout")
                    {
                        QWriter.RemoveAgency(ISigner.Manager, new Guid(_message));
                    }
                }
            }
        }
Exemplo n.º 8
0
        void QReader_QRemoveEvents(object sender, ReceiveCompletedEventArgs e)
        {
            QMessage _qmessage = e.Message.Body as QMessage;

            ISigner.WriteDebug(String.Format("remove: {0}, {1}, {2}, {3}, {4}", _qmessage.ProductId, _qmessage.Command, _qmessage.ProductId, _qmessage.IpAddress, _qmessage.Message));

            //if (_qmessage.ProductId == CPermit.QSlave.ProductId)
            //{
            //    CPermit.Stop();
            //}
        }
        public void RabbitMq_Subscribe()
        {
            var publisherSettings = GetConfig("publisherFanout");
            var consumerSettings  = GetConfig("subscriberFanout");

            // check if config exists
            Assert.NotNull(publisherSettings);
            Assert.NotNull(consumerSettings);

            IQueue cQueue = new RbmqQueue(new NullLoggerFactory(), consumerSettings, false);
            IQueue pQueue = new RbmqQueue(new NullLoggerFactory(), publisherSettings, true);

            cQueue.Clear();
            pQueue.Clear();


            var message = new QMessage()
            {
                Body       = "test",
                Properties = new QProperties()
                {
                    ReplyTo = "test"
                }
            };

            pQueue.Enqueue(message);

            QProperties    oProperties     = null;// = o.Properties;
            string         replyTo         = string.Empty;
            AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
            QMessage       recievedMsg     = null;

            cQueue.MessageRecieved += (m, o) =>
            {
                cQueue.Unsubscribe();
                recievedMsg = o;
                oProperties = o.Properties;
                replyTo     = o.Properties.ReplyTo;
                _autoResetEvent.Set();
            };

            cQueue.Subscribe();


            Assert.True(_autoResetEvent.WaitOne(3000));
            Assert.NotNull(recievedMsg);

            //Assert.That(oProperties, Is.Not.Null);
            //Assert.That(replyTo, Is.EqualTo("test"));
        }
Exemplo n.º 10
0
 internal static void OnMessage(MessageSource src, QMessage msg, QMessage origMsg, bool processed, BotModuleBase?processModule)
 {
     foreach (var service in Services)
     {
         try
         {
             service.OnMessageSafe(src, msg, origMsg, processed, processModule);
         }
         catch (Exception e)
         {
             throw new Exception($"Service Run Error: {service.GetType()}", e);
         }
     }
 }
Exemplo n.º 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="reader"></param>
 /// <param name="exception"></param>
 /// <param name="command"></param>
 /// <param name="label"></param>
 /// <param name="package"></param>
 /// <param name="app_secific"></param>
 /// <param name="priority"></param>
 /// <returns></returns>
 public bool WritePacket(
     QAgency sender, QAgency reader, string exception, string command, string label,
     XmlPackage package,
     int app_secific = 5, System.Messaging.MessagePriority priority = System.Messaging.MessagePriority.Normal
     )
 {
     using (QMessage _qmessage = new QMessage(sender)
     {
         Command = command,
         Package = package,
         UsePackage = false
     })
     {
         return(WritePacket(_qmessage, reader, exception, label, app_secific, priority));
     }
 }
Exemplo n.º 12
0
 public static void Producer()
 {
     try
     {
         var qName        = "lhtest1";
         var exchangeName = "fanoutchange1";
         var exchangeType = "fanout";//topic、fanout
         var routingKey   = "*";
         var uri          = new Uri("amqp://192.168.0.40:5672/");
         var factory      = new ConnectionFactory
         {
             UserName           = "******",
             Password           = "******",
             RequestedHeartbeat = 0,
             Endpoint           = new AmqpTcpEndpoint(uri)
         };
         using (var connection = factory.CreateConnection())
         {
             using (var channel = connection.CreateModel())
             {
                 //设置交换器的类型
                 channel.ExchangeDeclare(exchangeName, exchangeType);
                 //声明一个队列,设置队列是否持久化,排他性,与自动删除
                 channel.QueueDeclare(qName, true, false, false, null);
                 //绑定消息队列,交换器,routingkey
                 channel.QueueBind(qName, exchangeName, routingKey);
                 var properties = channel.CreateBasicProperties();
                 //队列持久化
                 properties.Persistent = true;
                 var m = new QMessage()
                 {
                     CreatDateTime = DateTime.Now, Name = "测试", IdCard = 123456
                 };
                 var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(m));   //序列化
                 //发送信息
                 channel.BasicPublish(exchangeName, routingKey, properties, body);
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            try
            {
                Console.Title = "CLIENT";
                var address = new Uri("http://localhost:64133/IContract");
                var binding = new BasicHttpBinding();

                var endpoint = new EndpointAddress(address);

                ChannelFactory <IContract> factory = new ChannelFactory <IContract>(binding, endpoint);

                var channel = factory.CreateChannel();

                QClass[]      arr  = new QClass[50];
                List <string> strs = new List <string>();
                var           rnd  = new Random();

                for (var i = 0; i < arr.Length; i++)
                {
                    arr[i] = new QClass(i + 1, RandomString(3), RandomString(3));
                    var serializedObj = SerializeObj(arr[i], arr[i].GetType());
                    var msg           = new QMessage
                    {
                        Obj = serializedObj
                    };
                    var t = arr[i].GetType();
                    msg.ClassName = t.Namespace + "." + t.Name;
                    strs.Add("Query_" + Convert.ToString(rnd.Next(3) + 1) + SerializeObj(msg, msg.GetType()));
                    channel.AddMessage(strs[i]);
                }
                channel.RemoveMessage(strs[9]);

                channel.RestoreQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadKey();
            }
        }
Exemplo n.º 14
0
 internal static bool OnMessage(ref MessageSource src, ref QMessage msg)
 {
     foreach (var middleware in Middlewares)
     {
         try
         {
             bool ctn = middleware.OnMessageSafe(ref src, ref msg);
             if (!ctn)
             {
                 return(false);
             }
         }
         catch (Exception e)
         {
             throw new Exception($"Middleware Run Error: {middleware.GetType()}", e);
         }
     }
     return(true);
 }
Exemplo n.º 15
0
        //-----------------------------------------------------------------------------------------------------------------------------
        // packet
        //-----------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="reader"></param>
        /// <param name="exception"></param>
        /// <param name="label"></param>
        /// <param name="app_secific"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public bool WritePacket(QMessage message, QAgency reader, string exception, string label, int app_secific, MessagePriority priority)
        {
            var _result = false;

            MessageQueue _messageQ = OpenQueue(QueuePath(reader));

            if (_messageQ != null)
            {
                _messageQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(QMessage) });
                //_messageQ.Formatter = new BinaryMessageFormatter();

                message.Exception = exception;
                message.Connected = CUnixTime.UtcNow;

                _result = WriteQueue(_messageQ, message, label, app_secific, priority);
            }

            return(_result);
        }
Exemplo n.º 16
0
            public LockState Run(MessageSource src, QMessage msg)
            {
                // 超时后直接跳过,之后 Lock 由超时方法移除
                if (timeout > TimeSpan.Zero && DateTime.Now - lastRun > timeout)
                {
                    return(LockState.Continue);
                }
                running = true;
                if (!predicate(src))
                {
                    running = false;
                    return(LockState.Continue);
                }

                LockState state = run(src, msg);

                if (state.Check(0b10))
                {
                    counter++;
                }
        public void RabbitMq_EnqueueFanout()
        {
            var publisherSettings = GetConfig("publisherFanout");
            var consumerSettings  = GetConfig("subscriberFanout");

            // check if config exists
            Assert.NotNull(publisherSettings);
            Assert.NotNull(consumerSettings);

            IQueue queue = new RbmqQueue(new NullLoggerFactory(), publisherSettings, consumerSettings);

            queue.PublisherSerializationSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented
            };

            queue.ConsumerSerializationSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented
            };

            var msg = new QMessage();
            var o   = new DummyObject()
            {
                Id = 1000, Name = "blalbal"
            };

            msg.Body = o;

            queue.Enqueue(msg);


            var a = queue.Dequeue <QMessage>();

            Assert.NotNull(a);
            var body = JsonConvert.DeserializeObject <DummyObject>(a.Body.ToString());

            Assert.True(body.Id == 1000);

            queue.Cleanup();
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="reader"></param>
        /// <param name="exception"></param>
        /// <param name="command"></param>
        /// <param name="label"></param>
        /// <param name="message"></param>
        /// <param name="kind_of_packing"></param>
        /// <param name="crypto_key"></param>
        /// <param name="app_secific"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public bool WritePacket(
            QAgency sender, QAgency reader, string exception, string command, string label,
            string message, MKindOfPacking kind_of_packing = MKindOfPacking.None, string crypto_key = "",
            int app_secific = 5, MessagePriority priority = MessagePriority.Normal
            )
        {
            var _result = false;

            if (String.IsNullOrEmpty(message) == false)
            {
                using (QMessage _qmessage = new QMessage(sender)
                {
                    Command = command,
                    Package = Serialization.SNG.WritePackage <string>(message, kind_of_packing, crypto_key),
                    UsePackage = true
                })
                {
                    _result = WritePacket(_qmessage, reader, exception, label, app_secific, priority);
                }
            }

            return(_result);
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public QMessage Dequeue <T>(bool ack = false)
        {
            QMessage       msg = null;
            BasicGetResult result;

            try
            {
                //IBasicProperties basicProperties = ConsumerChannel.CreateBasicProperties();
                //basicProperties.Persistent = true;
                lock (_lockSubscriber)
                {
                    bool noAck = false;
                    // get message from queue
                    result = ConsumerChannel.BasicGet(_consumerSettings.Queue, noAck);
                    if (result == null)
                    {
                        // No message available at this time.
                    }
                    else
                    {
                        IBasicProperties props = result.BasicProperties;

                        // get body
                        byte[] body = result.Body;

                        var json = Encoding.UTF8.GetString(body);

                        json = json.Replace("\"$type\":\"Infrastructure.Queueing.Model.QMessage, Infrastructure.Queueing\",", "");
                        json = json.Replace("\"$type\":\"Infra.Quotes.Brige.Models.BridgeQuote, Infra.Quotes.Bridge\",", "");

                        msg             = JsonConvert.DeserializeObject <QMessage>(json, _consumerSerializationSettings);
                        msg.DeliveryTag = result.DeliveryTag;
                        msg.Properties  = new QProperties()
                        {
                            AppId           = props.AppId,
                            ClusterId       = props.ClusterId,
                            ContentEncoding = props.ContentEncoding,
                            ContentType     = props.ContentType,
                            CorrelationId   = props.CorrelationId,
                            DeliveryMode    = props.DeliveryMode,
                            Expiration      = props.Expiration,
                            MessageId       = props.MessageId,
                            Priority        = props.Priority,
                            ReplyTo         = props.ReplyTo,
                            Type            = props.Type,
                            UserId          = props.UserId
                        };

                        if (ack)
                        {
                            ConsumerChannel.BasicAck(result.DeliveryTag, false);
                        }
                    }
                }
            }
            catch (OperationInterruptedException ex)
            {
                _logger.LogCritical($"Dequeue Error {ex.Message},Inner Exception:{ex.InnerException}, Stack: {ex.StackTrace}");
                throw;
            }

            return(msg);
        }
Exemplo n.º 20
0
 protected internal virtual bool OnMessage(ref MessageSource src, ref QMessage msg) => true;
Exemplo n.º 21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 public static void SendCommandQ(QMessage message)
 {
     CommandQ.Enqueue(message);
 }
Exemplo n.º 22
0
 private MessageBase ParseParameterToMessage(string message, object parameter, out short id)
 {
     MessageBase msgToSend = null;
     if (parameter == null) {
         id = DispatchEMessageId;
         EMessage emsg = new EMessage ();
         emsg.message = message;
         msgToSend = emsg;
     } else if (parameter is int) {
         id = DispatchIMessageId;
         IMessage imsg = new IMessage ();
         imsg.message = message;
         imsg.parameter = (int)parameter;
         msgToSend = imsg;
     } else if (parameter is float) {
         id = DispatchFMessageId;
         FMessage fmsg = new FMessage ();
         fmsg.message = message;
         fmsg.parameter = (float)parameter;
         msgToSend = fmsg;
     } else if (parameter is string) {
         id = DispatchSMessageId;
         SMessage smsg = new SMessage ();
         smsg.message = message;
         smsg.parameter = parameter as string;
         msgToSend = smsg;
     } else if (parameter is Vector3) {
         id = DispatchVMessageId;
         VMessage vmsg = new VMessage ();
         vmsg.message = message;
         vmsg.parameter = (Vector3)parameter;
         msgToSend = vmsg;
     } else if (parameter is Quaternion) {
         id = DispatchQMessageId;
         QMessage qmsg = new QMessage ();
         qmsg.message = message;
         qmsg.parameter = (Quaternion)parameter;
         msgToSend = qmsg;
     } else {
         id = -1;
         Debug.LogError ("Can't dispatch a non RPCable parameter");
     }
     return msgToSend;
 }
Exemplo n.º 23
0
 protected internal virtual void OnMessage(MessageSource src, QMessage msg, QMessage origMsg, bool processed, BotModuleBase?processModule)
 {
 }
Exemplo n.º 24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 public static void SendReceiveQ(QMessage message)
 {
     ReceiveQ.Enqueue(message);
 }
Exemplo n.º 25
0
 /// <inheritdoc/>
 public Task Enqueue(QMessage <T> item, bool isPoison) => Task.CompletedTask;
Exemplo n.º 26
0
        public void Enqueue(QMessage msg)
        {
            try
            {
                IBasicProperties basicProperties = PublishChannel.CreateBasicProperties();

                if (msg.Properties != null)
                {
                    basicProperties.Persistent = msg.Properties.Persistent;
                    if (!string.IsNullOrEmpty(msg.Properties.AppId))
                    {
                        basicProperties.AppId = msg.Properties.AppId;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.ClusterId))
                    {
                        basicProperties.ClusterId = msg.Properties.ClusterId;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.ContentEncoding))
                    {
                        basicProperties.ContentEncoding = msg.Properties.ContentEncoding;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.ContentType))
                    {
                        basicProperties.ContentType = msg.Properties.ContentType;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.CorrelationId))
                    {
                        basicProperties.CorrelationId = msg.Properties.CorrelationId;
                    }
                    if (msg.Properties.DeliveryMode != 0)
                    {
                        basicProperties.DeliveryMode = msg.Properties.DeliveryMode;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.Expiration))
                    {
                        basicProperties.Expiration = msg.Properties.Expiration;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.MessageId))
                    {
                        basicProperties.MessageId = msg.Properties.MessageId;
                    }
                    if (msg.Properties.Priority != 0)
                    {
                        basicProperties.Priority = msg.Properties.Priority;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.ReplyTo))
                    {
                        basicProperties.ReplyTo = msg.Properties.ReplyTo;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.Type))
                    {
                        basicProperties.Type = msg.Properties.Type;
                    }
                    if (!string.IsNullOrEmpty(msg.Properties.UserId))
                    {
                        basicProperties.UserId = msg.Properties.UserId;
                    }
                }

                // dead letters support
                //if (_settings.RetryDelay > 0)
                //{
                //    basicProperties.Headers.Add("x-delay", _settings.RetryDelay);
                //}

                lock (_lockPublisher)
                {
                    var jsonified     = JsonConvert.SerializeObject(msg, Formatting.None, _publisherSerializationSettings);
                    var messageBuffer = Encoding.UTF8.GetBytes(jsonified);

                    PublishChannel.BasicPublish(_publisherSettings.Exchange, _publisherSettings.RoutingKey, basicProperties, messageBuffer);
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical("Enqueue Error" + ex.Message + "Inner Exception:" + ex.InnerException);
                throw;
            }
        }