Пример #1
0
        public async Task WhenReceiveShouldValidateMaxNumberOfMessages()
        {
            //Arrange
            const int maxNumberOfMessages   = 0;
            var       clouldQueueClientMock = new Mock <CloudQueueClient>(MockBehavior.Loose, new Uri("http://localhost"), null, null);
            var       clouldQueueMock       = new Mock <CloudQueue>(MockBehavior.Loose, new Uri("http://localhost"), null);
            var       configurationMock     = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            clouldQueueMock.Setup(x => x.GetMessageAsync())
            .ReturnsAsync(new CloudQueueMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msg))))
            .Verifiable();

            clouldQueueClientMock.Setup(x => x.GetQueueReference(It.IsAny <string>()))
            .Returns(clouldQueueMock.Object)
            .Verifiable();

            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueAzureStorageQueue(clouldQueueClientMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            Func <Task> act = async() => await queue.Receive <TestMessage>(maxNumberOfMessages)
                              .GetAsyncEnumerator()
                              .MoveNextAsync();

            //Assert
            await Assert.ThrowsAsync <ArgumentException>(act);
        }
Пример #2
0
        public async Task ShouldMarkAsReceived()
        {
            //Arrange
            var consumerMock      = new Mock <IConsumer <Ignore, string> >();
            var producerMock      = new Mock <IProducer <Null, string> >();
            var consumeResultMock = new Mock <ConsumeResult <Ignore, string> >();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            consumerMock.Setup(x => x.StoreOffset(It.IsAny <ConsumeResult <Ignore, string> >()))
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueKafka(consumerMock.Object, producerMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            await queue.Received(msg);

            //Assert
            consumerMock.VerifyAll();
        }
Пример #3
0
        public async Task ShouldReceive()
        {
            //Arrange
            var modelMock         = new Mock <IModel>();
            var connectionMock    = new Mock <IConnection>();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            modelMock.Setup(x => x.BasicGet(It.IsAny <string>(), It.IsAny <bool>()))
            .Returns(new BasicGetResult(0, false, "", "", 1, null, Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msg))))
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);
            connectionMock.Setup(x => x.CreateModel()).Returns(modelMock.Object);

            var queue = new MessageQueueRabbitMq(connectionMock.Object, messageQueueOptions,
                                                 new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            var qtd = 0;

            await foreach (var message in queue.Receive <TestMessage>(1))
            {
                qtd++;
            }

            //Assert
            modelMock.VerifyAll();
        }
Пример #4
0
        public async Task WhenReceiveShouldValidateMaxNumberOfMessages()
        {
            //Arrange
            const int maxNumberOfMessages = 0;
            var       modelMock           = new Mock <IModel>();
            var       connectionMock      = new Mock <IConnection>();
            var       configurationMock   = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            modelMock.Setup(x => x.BasicGet(It.IsAny <string>(), It.IsAny <bool>()))
            .Returns(new BasicGetResult(0, false, "", "", 1, null, Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msg))))
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueRabbitMq(connectionMock.Object, messageQueueOptions,
                                                 new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            async Task act() => await queue.Receive <TestMessage>(maxNumberOfMessages)
            .GetAsyncEnumerator()
            .MoveNextAsync();

            //Assert
            await Assert.ThrowsAsync <ArgumentException>(act);
        }
Пример #5
0
        public async Task ShouldMarkAsReceived()
        {
            //Arrange
            var modelMock         = new Mock <IModel>();
            var connectionMock    = new Mock <IConnection>();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            (ulong DeliveryTag, CancellationTokenSource CancellationTokenSource)queueData = GetQueueDataStub();

            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString(), QueueData = queueData
            };

            modelMock.Setup(x => x.BasicAck(It.IsAny <ulong>(), It.IsAny <bool>()))
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);
            connectionMock.Setup(x => x.CreateModel()).Returns(modelMock.Object);

            var queue = new MessageQueueRabbitMq(connectionMock.Object, messageQueueOptions,
                                                 new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            await queue.Received(msg);

            //Assert
            connectionMock.VerifyAll();
        }
Пример #6
0
        public async Task ShouldSend()
        {
            //Arrange
            var modelMock         = new Mock <IModel>();
            var connectionMock    = new Mock <IConnection>();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            modelMock.Setup(x => x.BasicPublish(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <IBasicProperties>(), It.IsAny <ReadOnlyMemory <byte> >()))
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);
            connectionMock.Setup(x => x.CreateModel()).Returns(modelMock.Object);

            var queue = new MessageQueueRabbitMq(connectionMock.Object, messageQueueOptions,
                                                 new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            //Act
            await queue.Send(msg);

            //Assert
            modelMock.VerifyAll();
        }
        HybridDbMessageQueue StartQueue(MessageQueueOptions options = null)
        {
            options = (options ?? new MessageQueueOptions())
                      .ReplayEvents(TimeSpan.FromSeconds(60));

            return(Using(new HybridDbMessageQueue(store, handler, options)));
        }
Пример #8
0
        /// <summary>
        /// Activates notification events. An application can now register to PowerNotify and be
        /// notified when a power notification is received.
        /// </summary>
        public void EnableNotifications()
        {
            // Set the message queue options
            MessageQueueOptions Options = new MessageQueueOptions();

            // Size in bytes ( 5 * 4)
            Options.Size = (uint)Marshal.SizeOf(Options);
            // Allocate message buffers on demand and to free the message buffers after they are read
            Options.Flags = MSGQUEUE_NOPRECOMMIT;
            // Number of messages in the queue.
            Options.MaxMessages = 32;
            // Number of bytes for each message, do not set to zero.
            Options.MaxMessage = 512;
            // Set to true to request read access to the queue.
            Options.ReadAccess = 1;     // True

            // Create the queue and request power notifications on it
            hMsgQ = CECreateMsgQueue("PowerNotifications", ref Options);

            hReq = CERequestPowerNotifications(hMsgQ, POWER_NOTIFY_ALL);

            // If the above succeed
            if (hMsgQ != IntPtr.Zero && hReq != IntPtr.Zero)
            {
                //powerQueue = new Queue();

                // Create an event so that we can kill the thread when we want
                powerThreadAbort = new AutoResetEvent(false);

                // Create the power watcher thread
                Thread pnt = new Thread(new ThreadStart(PowerNotifyThread));
                pnt.IsBackground = true;
                pnt.Start();
            }
        }
Пример #9
0
        public async Task ShouldSend()
        {
            //Arrange
            var consumerMock      = new Mock <IConsumer <Ignore, string> >();
            var producerMock      = new Mock <IProducer <Null, string> >();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            producerMock.Setup(x => x.ProduceAsync(It.IsAny <string>(), It.IsAny <Message <Null, string> >(), default(CancellationToken)))
            .Verifiable();

            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueKafka(consumerMock.Object, producerMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));
            var msg   = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            //Act
            await queue.Send(msg);

            //Assert
            producerMock.VerifyAll();
        }
Пример #10
0
        public async Task ShouldSend()
        {
            //Arrange
            var clouldQueueClientMock = new Mock <CloudQueueClient>(MockBehavior.Loose, new Uri("http://localhost"), null, null);
            var clouldQueueMock       = new Mock <CloudQueue>(MockBehavior.Loose, new Uri("http://localhost"), null);
            var configurationMock     = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            clouldQueueMock.Setup(x => x.AddMessageAsync(It.IsAny <CloudQueueMessage>()))
            .Returns(Task.FromResult(new CloudQueueMessage(new byte[0])))
            .Verifiable();

            clouldQueueClientMock.Setup(x => x.GetQueueReference(It.IsAny <string>()))
            .Returns(clouldQueueMock.Object)
            .Verifiable();

            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueAzureStorageQueue(clouldQueueClientMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));
            var msg   = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            //Act
            await queue.Send(msg);

            //Assert
            clouldQueueClientMock.VerifyAll();
            clouldQueueMock.VerifyAll();
        }
Пример #11
0
        public async Task ShouldSend()
        {
            //Arrange
            var amazonSqsMock     = new Mock <IAmazonSQS>();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            amazonSqsMock.Setup(x => x.SendMessageAsync(It.IsAny <SendMessageRequest>(), CancellationToken.None))
            .ReturnsAsync(new SendMessageResponse())
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueSqs(amazonSqsMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));
            var msg   = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            //Act
            await queue.Send(msg);

            //Assert
            amazonSqsMock.VerifyAll();
        }
Пример #12
0
        public void Subscribe <T>(Func <T, Task> handler, MessageQueueOptions options = null) where T : class
        {
            var type = typeof(T);

            var key = type.FullName;

            Subscribe <T>(key, handler, options);
        }
Пример #13
0
 public async Task PublishAsync(string key, object value, MessageQueueOptions options = null)
 {
     if (options?.SpecificKey != null)
     {
         var specificKeyString = _serializer.Serialize(options.SpecificKey, options?.SerializerOptions);
         key = $"{key}_{specificKeyString}";
     }
     string serialized = _serializer.Serialize(value, options?.SerializerOptions);
     await _subscriber.PublishAsync(key, serialized);
 }
Пример #14
0
        public async Task PublishAsync(object value, MessageQueueOptions options = null)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var key = value.GetType().FullName;

            await PublishAsync(key, value, options);
        }
Пример #15
0
        public void Subscribe <T>(string key, Func <T, Task> handler, MessageQueueOptions options = null) where T : class
        {
            if (options?.SpecificKey != null)
            {
                var specificKeyString = _serializer.Serialize(options.SpecificKey, options?.SerializerOptions);
                key = $"{key}_{specificKeyString}";
            }

            _subscriber.Subscribe(key, (channel, value) =>
            {
                var deserialized = _serializer.Deserialize <T>(value, options?.SerializerOptions);
                handler.Invoke(deserialized);
            });
        }
Пример #16
0
        public async Task ShouldReceiveWithCancellationToken()
        {
            //Arrange
            const int delay             = 1;
            var       cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(delay)).Token;
            var       consumerMock      = new Mock <IConsumer <Ignore, string> >();
            var       producerMock      = new Mock <IProducer <Null, string> >();
            var       consumeResultMock = new Mock <ConsumeResult <Ignore, string> >();
            var       configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            consumerMock.SetupGet(x => x.Subscription).Returns(() => new List <string>()).Verifiable();
            consumerMock.Setup(x => x.Subscribe(It.IsAny <string>())).Verifiable();
            consumerMock.Setup(x => x.Consume(cancellationToken))
            .Returns(new ConsumeResult <Ignore, string>()
            {
                Message = new Message <Ignore, string>()
                {
                    Value = JsonConvert.SerializeObject(msg)
                }
            })
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueKafka(consumerMock.Object, producerMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            var qtd = 0;

            await foreach (var message in queue.Receive <TestMessage>(cancellationToken))
            {
                qtd++;
            }

            //Assert
            consumerMock.VerifyAll();
            Assert.True(qtd > 0);
        }
Пример #17
0
        public async Task ShouldReceiveWithCancellationToken()
        {
            //Arrange
            const int delay                 = 1;
            var       cancellationToken     = new CancellationTokenSource(TimeSpan.FromSeconds(delay)).Token;
            var       clouldQueueClientMock = new Mock <CloudQueueClient>(MockBehavior.Loose, new Uri("http://localhost"), null, null);
            var       clouldQueueMock       = new Mock <CloudQueue>(MockBehavior.Loose, new Uri("http://localhost"), null);
            var       configurationMock     = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();

            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            clouldQueueMock.Setup(x => x.GetMessagesAsync(It.IsAny <int>(), cancellationToken))
            .ReturnsAsync(new CloudQueueMessage[1]
            {
                new CloudQueueMessage(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msg)))
            }).Verifiable();

            clouldQueueClientMock.Setup(x => x.GetQueueReference(It.IsAny <string>()))
            .Returns(clouldQueueMock.Object)
            .Verifiable();

            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueAzureStorageQueue(clouldQueueClientMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            var qtd = 0;

            await foreach (var message in queue.Receive <TestMessage>(cancellationToken))
            {
                qtd++;
            }

            //Assert
            clouldQueueClientMock.VerifyAll();
            clouldQueueMock.VerifyAll();
            Assert.True(qtd > 0);
        }
Пример #18
0
        public async Task ShouldReceiveWithCancellationToken()
        {
            //Arrange
            const int delay             = 1;
            var       cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(delay)).Token;
            var       amazonSqsMock     = new Mock <IAmazonSQS>();
            var       configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            amazonSqsMock.Setup(x => x.ReceiveMessageAsync(It.IsAny <ReceiveMessageRequest>(), cancellationToken))
            .ReturnsAsync(new ReceiveMessageResponse()
            {
                Messages = new List <Message>()
                {
                    new Message()
                    {
                        Body          = JsonConvert.SerializeObject(msg),
                        ReceiptHandle = Guid.NewGuid().ToString()
                    }
                }
            })
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueSqs(amazonSqsMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            var qtd = 0;

            await foreach (var message in queue.Receive <TestMessage>(cancellationToken))
            {
                qtd++;
            }

            //Assert
            amazonSqsMock.VerifyAll();
            Assert.True(qtd > 0);
        }
Пример #19
0
        public RabbitMqMessageSender(
            IOptions <MessageQueueOptions> messageQueueOptions,
            IServiceScopeFactory serviceScopeFactory,
            ILoggerFactory loggerFactory)
        {
            _processMessageMethod = typeof(RabbitMqMessageSender).GetMethod("ProcessMessage", BindingFlags.Instance | BindingFlags.NonPublic);
            _messageQueueOptions  = messageQueueOptions.Value;
            _serviceScopeFactory  = serviceScopeFactory;
            _logger = loggerFactory.CreateLogger <RabbitMqMessageSender>();

            _bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
            {
                var value = messageQueueOptions.Value;
                sbc.Host(new Uri($"rabbitmq://{value.RabbitMqHost}"), h =>
                {
                    h.Username(value.RabbitMqUsername);
                    h.Password(value.RabbitMqPassword);
                });
            });
        }
        public static IServiceCollection AddQueueClient(this IServiceCollection services, IConfiguration configuration)
        {
            var positionOptions = new MessageQueueOptions();

            configuration.GetSection(MessageQueueOptions.SectionName).Bind(positionOptions);

            positionOptions.ConnectionString.ThrowIfNullOrEmpty(nameof(MessageQueueOptions.ConnectionString));
            positionOptions.QueueName.ThrowIfNullOrEmpty(nameof(MessageQueueOptions.QueueName));

            services.AddTransient <IQueueService, StorageQueueService>();
            services.AddTransient <QueueClient>(x => {
                var options = new QueueClientOptions
                {
                    MessageEncoding = QueueMessageEncoding.Base64
                };

                return(new QueueClient(positionOptions.ConnectionString, positionOptions.QueueName, options));
            });

            return(services);
        }
Пример #21
0
        public async Task WhenReceiveShouldValidateMaxNumberOfMessages()
        {
            //Arrange
            const int maxNumberOfMessages = 0;
            var       consumerMock        = new Mock <IConsumer <Ignore, string> >();
            var       producerMock        = new Mock <IProducer <Null, string> >();
            var       consumeResultMock   = new Mock <ConsumeResult <Ignore, string> >();
            var       configurationMock   = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            consumerMock.SetupGet(x => x.Subscription).Returns(() => new List <string>()).Verifiable();
            consumerMock.Setup(x => x.Subscribe(It.IsAny <string>())).Verifiable();
            consumerMock.Setup(x => x.Consume(TimeSpan.FromSeconds(5)))
            .Returns(new ConsumeResult <Ignore, string>()
            {
                Message = new Message <Ignore, string>()
                {
                    Value = JsonConvert.SerializeObject(msg)
                }
            })
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueKafka(consumerMock.Object, producerMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            Func <Task> act = async() => await queue.Receive <TestMessage>(maxNumberOfMessages)
                              .GetAsyncEnumerator()
                              .MoveNextAsync();

            //Assert
            await Assert.ThrowsAsync <ArgumentException>(act);
        }
Пример #22
0
        public async Task WhenReceiveShouldValidateMaxNumberOfMessages(int maxNumberOfMessages)
        {
            //Arrange
            var amazonSqsMock     = new Mock <IAmazonSQS>();
            var configurationMock = new Mock <IConfiguration>();

            var messageQueueOptions = new MessageQueueOptions();
            var msg = new TestMessage()
            {
                Id = Guid.NewGuid().ToString()
            };

            amazonSqsMock.Setup(x => x.ReceiveMessageAsync(It.IsAny <ReceiveMessageRequest>(), CancellationToken.None))
            .ReturnsAsync(new ReceiveMessageResponse()
            {
                Messages = new List <Message>()
                {
                    new Message()
                    {
                        Body          = JsonConvert.SerializeObject(msg),
                        ReceiptHandle = Guid.NewGuid().ToString()
                    }
                }
            })
            .Verifiable();
            configurationMock.SetupGet(x => x[It.IsAny <string>()]).Returns(string.Empty);

            var queue = new MessageQueueSqs(amazonSqsMock.Object, messageQueueOptions, new MessageQueueInfo(messageQueueOptions, configurationMock.Object));

            //Act
            async Task act() => await queue.Receive <TestMessage>(maxNumberOfMessages)
            .GetAsyncEnumerator()
            .MoveNextAsync();

            //Assert
            await Assert.ThrowsAsync <ArgumentException>(act);
        }
Пример #23
0
 private static extern IntPtr CECreateMsgQueue(string Name, ref MessageQueueOptions Options);
Пример #24
0
        /// <summary>
        /// Activates notification events. An application can now register to PowerNotify and be 
        /// notified when a power notification is received.
        /// </summary>
        public void EnableNotifications()
        {
            // Set the message queue options
            MessageQueueOptions Options = new MessageQueueOptions();

            // Size in bytes ( 5 * 4)
            Options.Size = (uint)Marshal.SizeOf(Options);
            // Allocate message buffers on demand and to free the message buffers after they are read
            Options.Flags = MSGQUEUE_NOPRECOMMIT;
            // Number of messages in the queue.
            Options.MaxMessages = 32;
            // Number of bytes for each message, do not set to zero.
            Options.MaxMessage = 512;
            // Set to true to request read access to the queue.
            Options.ReadAccess = 1;	// True

            // Create the queue and request power notifications on it
            hMsgQ = CECreateMsgQueue("PowerNotifications", ref Options);

            hReq = CERequestPowerNotifications(hMsgQ, POWER_NOTIFY_ALL);

            // If the above succeed
            if (hMsgQ != IntPtr.Zero && hReq != IntPtr.Zero)
            {
                //powerQueue = new Queue();

                // Create an event so that we can kill the thread when we want
                powerThreadAbort = new AutoResetEvent(false);

                // Create the power watcher thread
                Thread pnt = new Thread(new ThreadStart(PowerNotifyThread));
                pnt.IsBackground = true;
                pnt.Start();
            }
        }
Пример #25
0
 private static extern IntPtr CECreateMsgQueue(string Name, ref MessageQueueOptions Options);