Exemplo n.º 1
0
        /// <summary>
        ///     Get message json body
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string GetJson(this Message message)
        {
            // https://github.com/Azure/azure-service-bus/issues/114 as is Server EnqueuedTimeUtc we use this to serialize the message

            //message.TimeToLive = TimeSpan.FromSeconds(10);
            var systemProperties = new Message.SystemPropertiesCollection();

            // systemProperties.EnqueuedTimeUtc = DateTime.UtcNow.AddMinutes(1);
            var bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
                           BindingFlags.SetProperty;

            systemProperties.GetType().InvokeMember("EnqueuedTimeUtc", bindings, Type.DefaultBinder, systemProperties,
                                                    new object[] { });

            // workaround "ThrowIfNotReceived" by setting "SequenceNumber" value null
            systemProperties.GetType().InvokeMember("SequenceNumber", bindings, Type.DefaultBinder, systemProperties,
                                                    new object[] { });

            // message.systemProperties = systemProperties;
            bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty;
            message.GetType().InvokeMember("SystemProperties", bindings, Type.DefaultBinder, message,
                                           new object[] { systemProperties });

            var json = JsonConvert.SerializeObject(message);

            return(json);
        }
Exemplo n.º 2
0
        public async Task ProcessMessageAsync_Success()
        {
            var message          = new CustomMessage();
            var systemProperties = new Message.SystemPropertiesCollection();

            typeof(Message.SystemPropertiesCollection).GetProperty("SequenceNumber").SetValue(systemProperties, 1);
            typeof(Message.SystemPropertiesCollection).GetProperty("DeliveryCount").SetValue(systemProperties, 55);
            typeof(Message.SystemPropertiesCollection).GetProperty("EnqueuedTimeUtc").SetValue(systemProperties, DateTime.Now);
            typeof(Message.SystemPropertiesCollection).GetProperty("LockedUntilUtc").SetValue(systemProperties, DateTime.Now);
            typeof(Message).GetProperty("SystemProperties").SetValue(message, systemProperties);

            message.MessageId = Guid.NewGuid().ToString();
            CancellationToken cancellationToken = new CancellationToken();

            _mockMessageProcessor.Setup(p => p.BeginProcessingMessageAsync(message, cancellationToken)).ReturnsAsync(true);

            FunctionResult result = new FunctionResult(true);

            _mockExecutor.Setup(p => p.TryExecuteAsync(It.Is <TriggeredFunctionData>(q => q.TriggerValue == message), cancellationToken)).ReturnsAsync(result);

            _mockMessageProcessor.Setup(p => p.CompleteProcessingMessageAsync(message, result, cancellationToken)).Returns(Task.FromResult(0));

            await _listener.ProcessMessageAsync(message, CancellationToken.None);

            _mockMessageProcessor.VerifyAll();
            _mockExecutor.VerifyAll();
            _mockMessageProcessor.VerifyAll();
        }
Exemplo n.º 3
0
            Message GenerateMessage(object message)
            {
                Message asbMessage;

                using (var stream = new MemoryStream())
                {
                    messageSerializer.Serialize(message, stream);
                    asbMessage = new Message(stream.ToArray());
                }

                asbMessage.UserProperties["NServiceBus.EnclosedMessageTypes"] = message.GetType().FullName;

                var systemProperties = new Message.SystemPropertiesCollection();
                // sequence number is required to prevent SystemPropertiesCollection from throwing on the getters
                var fieldInfo = typeof(Message.SystemPropertiesCollection).GetField("sequenceNumber", BindingFlags.NonPublic | BindingFlags.Instance);

                fieldInfo.SetValue(systemProperties, 123);
                // set delivery count to 1
                var deliveryCountProperty = typeof(Message.SystemPropertiesCollection).GetProperty("DeliveryCount");

                deliveryCountProperty.SetValue(systemProperties, 1);
                // assign test message mocked system properties
                var property = typeof(Message).GetProperty("SystemProperties");

                property.SetValue(asbMessage, systemProperties);

                return(asbMessage);
            }
        protected override async Task ProcessMessage(Order order, string messageId, Message.SystemPropertiesCollection systemProperties, IDictionary <string, object> userProperties, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Processing order {OrderId} for {OrderAmount} units of {OrderArticle} bought by {CustomerFirstName} {CustomerLastName}", order.Id, order.Amount, order.ArticleNumber, order.Customer.FirstName, order.Customer.LastName);

            await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);

            Logger.LogInformation("Order {OrderId} processed", order.Id);
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="messageId">Unique identifier of the message</param>
        /// <param name="systemProperties">Contextual properties provided on the message provided by the Service Bus runtime</param>
        /// <param name="properties">Contextual properties provided on the message provided by the message publisher</param>
        public AzureServiceBusMessageContext(string messageId, Message.SystemPropertiesCollection systemProperties,
                                             IDictionary <string, object> properties)
            : base(messageId, properties)
        {
            Guard.NotNull(systemProperties, nameof(systemProperties));

            SystemProperties = systemProperties;
            LockToken        = systemProperties.LockToken;
            DeliveryCount    = systemProperties.DeliveryCount;
        }
        public MessageBuilder WithLockToken(Guid lockToken)
        {
            Message.SystemPropertiesCollection systemProperties = _message.SystemProperties;
            Type type = systemProperties.GetType();

            type.GetMethod("set_LockTokenGuid", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(systemProperties, new object[] { lockToken });
            type.GetMethod("set_SequenceNumber", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(systemProperties, new object[] { 0 });

            return(this);
        }
Exemplo n.º 7
0
        public void Run_DoesNotThrowException()
        {
            // Arrange
            var state        = new SessionWorkflowState();
            var dummyMessage = new Message {
                MessageId = "1"
            };

            // Workaround to set internal get properties
            var systemProperties = new Message.SystemPropertiesCollection();

            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.SequenceNumber)).SetValue(systemProperties, 1);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.DeliveryCount)).SetValue(systemProperties, 1);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.EnqueuedTimeUtc)).SetValue(systemProperties, DateTime.Now);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.LockedUntilUtc)).SetValue(systemProperties, DateTime.Now);
            typeof(Message).GetProperty(nameof(dummyMessage.SystemProperties)).SetValue(dummyMessage, systemProperties);

            var mockSession = Mock.Of <IMessageSession>(MockBehavior.Strict);

            Mock.Get(mockSession)
            .SetupGet(s => s.SessionId)
            .Returns("session-1");

            var mockContractEventSessionManager = Mock.Of <IContractEventSessionManager>(MockBehavior.Strict);

            Mock.Get(mockContractEventSessionManager)
            .Setup(m => m.ProcessSessionMessageAsync(mockSession, dummyMessage))
            .ReturnsAsync(state)
            .Verifiable();

            var mockLogger = Mock.Of <ILogger>(MockBehavior.Strict);

            Mock.Get(mockLogger)
            .Setup(l => l.Log(LogLevel.Information, It.IsAny <EventId>(), It.IsAny <It.IsAnyType>(), null, It.IsAny <Func <It.IsAnyType, Exception, string> >()));

            Mock.Get(mockLogger)
            .Setup(l => l.BeginScope(It.IsAny <string>()))
            .Returns(It.IsAny <IDisposable>());

            var function = new ContractEventProcessorFunction(mockContractEventSessionManager);

            // Act
            Func <Task> act = async() => { await function.Run(dummyMessage, mockSession, mockLogger); };

            // Assert
            act.Should().NotThrow();
            Mock.Get(mockContractEventSessionManager).Verify();

            Mock.Get(mockLogger).VerifyAll();

            Mock.Get(mockSession)
            .VerifyGet(s => s.SessionId, Times.Exactly(3));
        }
Exemplo n.º 8
0
        private IDictionary <string, object> ConvertSystemPropertiesToIDictonary(Message.SystemPropertiesCollection systemProperties)
        {
            IDictionary <string, object> res = new Dictionary <string, object>();

            res.Add("DeadLetterSource", systemProperties.DeadLetterSource);
            res.Add("DeliveryCount", systemProperties.DeliveryCount);
            res.Add("EnqueuedSequenceNumber", systemProperties.EnqueuedSequenceNumber);
            res.Add("EnqueuedTimeUtc", systemProperties.EnqueuedTimeUtc);
            res.Add("IsLockTokenSet", systemProperties.IsLockTokenSet);
            res.Add("IsReceived", systemProperties.IsReceived);
            res.Add("LockedUntilUtc", systemProperties.LockedUntilUtc);
            res.Add("LockToken", systemProperties.LockToken);
            res.Add("SequenceNumber", systemProperties.SequenceNumber);

            return(res);
        }
Exemplo n.º 9
0
        private static Message GetDummyMessage(ContractEvent expectedBodyMessage = null, int deliveryCount = 1)
        {
            Message dummyMessage = new Message
            {
                MessageId = "1",
                Body      = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(expectedBodyMessage ?? new ContractEvent()))
            };

            //Workaround to set internal get properties
            var systemProperties = new Message.SystemPropertiesCollection();

            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.SequenceNumber)).SetValue(systemProperties, 1);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.DeliveryCount)).SetValue(systemProperties, deliveryCount);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.EnqueuedTimeUtc)).SetValue(systemProperties, DateTime.Now);
            typeof(Message.SystemPropertiesCollection).GetProperty(nameof(systemProperties.LockedUntilUtc)).SetValue(systemProperties, DateTime.Now);
            typeof(Message).GetProperty(nameof(dummyMessage.SystemProperties)).SetValue(dummyMessage, systemProperties);
            return(dummyMessage);
        }
Exemplo n.º 10
0
 protected abstract Task ProcessMessage(TMessage order, string messageId, Message.SystemPropertiesCollection systemProperties, IDictionary <string, object> userProperties, CancellationToken cancellationToken);
Exemplo n.º 11
0
 protected override async Task ProcessMessage(StoreCreated store, string messageId, Message.SystemPropertiesCollection systemProperties, IDictionary <string, object> userProperties, CancellationToken cancellationToken)
 {
 }
        protected override async Task ProcessMessage(ProductCreated product, string messageId, Message.SystemPropertiesCollection systemProperties, IDictionary <string, object> userProperties, CancellationToken cancellationToken)
        {
            var serviceName = this._configuration["AzureSearchIndex:ServiceName"];
            var serviceKey  = this._configuration["AzureSearchIndex:ServiceAdminKey"];
            var indexName   = this._configuration["AzureSearchIndex:CatalogIndex"];

            var serviceClient = new SearchServiceClient(serviceName, new SearchCredentials(serviceKey));
            var indexClient   = serviceClient.Indexes.GetClient(indexName);

            var actions = new IndexAction <CatalogDataIndex>[]
            {
                IndexAction.Upload(
                    new CatalogDataIndex
                {
                    Id           = product.ProductId.ToString(),
                    Name         = product.Name,
                    Description  = product.Description,
                    Brand        = product.BrandId,
                    BrandName    = product.BrandName,
                    Price        = Convert.ToDouble(product.BasePrice),
                    SpecialPrice = Convert.ToDouble(product.SpecialPrice),
                    Stock        = product.Stock,
                    Store        = product.SellerId,
                    StoreName    = product.SellerName,
                }
                    ),
            };

            var batch = IndexBatch.New(actions);

            try
            {
                await indexClient.Documents.IndexAsync(batch);
            }
            catch (IndexBatchException e)
            {
                // When a service is under load, indexing might fail for some documents in the batch.
                // Depending on your application, you can compensate by delaying and retrying.
                // For this simple demo, we just log the failed document keys and continue.
                this._logger.LogError(
                    "Failed to index some of the documents: {0}",
                    String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
            }
            catch (Exception e)
            {
                this._logger.LogError(e.ToString());
            }
        }