public async Task Handle_JustCalled_CreateChallengeAndSetToQuiz()
        {
            // Arrange
            var quizId        = "42";
            var mathChallenge = new MathChallenge()
            {
                Question    = "2+2=4?",
                IsCompleted = false,
                IsCorrect   = true
            };

            _mathChallengeServiceMock
            .Setup(m => m.CreateChallenge())
            .Returns(mathChallenge);

            var @event = new ChallengeStarting
            {
                QuizId    = quizId,
                StartDate = DateTimeOffset.UtcNow
            };

            // Act
            await _handler.Handle(@event);

            // Assert
            _mathChallengeServiceMock.Verify(x => x.CreateChallenge());
            _mathChallengeServiceMock.VerifyNoOtherCalls();
            _quizServiceMock.Verify(x => x.SetChallengeToQuiz(quizId, mathChallenge.Question, mathChallenge.IsCorrect));
            _quizServiceMock.VerifyNoOtherCalls();
        }
Exemplo n.º 2
0
        public async Task CallHandlerAsync <TRequest, TResponse, TIntegrationEventHandler>(ILifetimeScope scope,
                                                                                           QueueOptions options) where TRequest : IntegrationEvent
            where TResponse : IntegrationEvent
        {
            EventingBasicConsumer consumer = BuildChannel(options);

            consumer.Received += async(model, args) =>
            {
                TRequest request = null;

                using (ILifetimeScope innerScope = scope.BeginLifetimeScope())
                    using (MessageSerializer serializaer = new MessageSerializer())
                        using (IIntegrationEventHandler <TRequest, TResponse> handler = innerScope.Resolve <IIntegrationEventHandler <TRequest, TResponse> >())
                        {
                            IBasicProperties props      = args.BasicProperties;
                            IBasicProperties replyProps = Channel.CreateBasicProperties();
                            replyProps.CorrelationId = props.CorrelationId;

                            request = Activator.CreateInstance <TRequest>();

                            if (args.Body.Length > 0)
                            {
                                request = serializaer.Deserialize <TRequest>(args.Body.ToArray())[0];
                            }

                            TResponse response = await handler.Handle(request);

                            Channel.BasicPublish("", props.ReplyTo, replyProps, serializaer.Serialize(response)[0]);
                            Channel.BasicAck(args.DeliveryTag, false);
                        }
            };
        }
        public async Task Handle()
        {
            await _notice.NotifyAsync(async() =>
            {
                var dataEvent = new DataSensorsAddedIntegrationEvent <DataSensorsAddedContent>
                                    (new DataSensorsAddedContent("Data added."), "SmartHome.Data.Api", null);

                await _dataHandler.Handle(dataEvent);
            });
        }
Exemplo n.º 4
0
        public void Subscribe <T>(IIntegrationEventHandler <T> eventHandler) where T : IntegrationEvent
        {
            string exchangeName = "";
            string queueName    = "";

            if (typeof(T) == typeof(UserCreatedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameAdd;
                queueName    = EventBusInfo.queueNameAdd;
            }
            else
            if (typeof(T) == typeof(UserEditedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameEdit;
                queueName    = EventBusInfo.queueNameEdit;
            }
            else
            if (typeof(T) == typeof(UserRemovedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameDelete;
                queueName    = EventBusInfo.queueNameDelete;
            }

            _channel.ExchangeDeclare(
                exchange: exchangeName,
                type: "fanout",
                durable: true
                );
            _channel.QueueDeclare(queue: queueName,
                                  durable: true,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);
            _channel.QueueBind(
                queue: queueName,
                exchange: exchangeName,
                routingKey: ""
                );
            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += async(model, args) =>
            {
                try
                {
                    string message = Encoding.UTF8.GetString(args.Body);
                    var    @event  = JsonConvert.DeserializeObject <T>(message);
                    await eventHandler.Handle(@event);
                }
                catch (Exception) { }
            };
            _channel.BasicConsume(queue: queueName,
                                  autoAck: true,
                                  consumer: consumer);
        }
Exemplo n.º 5
0
 public void SubscribeDynamic(string eventName, IIntegrationEventHandler <dynamic> handler)
 {
     try
     {
         this.OnMessageReceived += (async(msg, topic) =>
         {
             if (topic.Equals(eventName))
             {
                 await handler.Handle(msg);
             }
         });
         this.DoInternalSubscription(eventName);
         this.memory.AddDynamicSubscription(eventName, handler);
     }
     catch (NMSException ex)
     {
         throw new NMSException("Could not subscribe dynamically ", ex);
     }
 }
Exemplo n.º 6
0
        public async Task SubscribeAsync <TRequestEvent, TIntegrationEventHandler>(ILifetimeScope scope,
                                                                                   QueueOptions options = null) where TRequestEvent : IntegrationEvent
            where TIntegrationEventHandler : IIntegrationEventHandler <TRequestEvent>
        {
            Tuple <string, EventingBasicConsumer> channelData = BuildChannel(options);

            channelData.Item2.Received += async(model, args) =>
            {
                using (ILifetimeScope innerScope = scope.BeginLifetimeScope())
                    using (MessageSerializer serializaer = new MessageSerializer())
                        using (IIntegrationEventHandler <TRequestEvent> handler = innerScope.Resolve <IIntegrationEventHandler <TRequestEvent> >())
                        {
                            TRequestEvent request = serializaer.Deserialize <TRequestEvent>(args.Body.ToArray())[0];
                            await handler.Handle(request);
                        }
            };

            Channel.BasicConsume(channelData.Item1, true, channelData.Item2);
        }
Exemplo n.º 7
0
 public void Subscribe <T>(string eventName, IIntegrationEventHandler <T> integrationEventHandler)
     where T : IntegrationEvent
 {
     try
     {
         this.OnMessageReceived += (async(msg, topic) =>
         {
             if (topic.Equals(eventName) || topic.Equals("topic://" + eventName))
             {
                 await integrationEventHandler.Handle((T)msg);
             }
         });
         this.DoInternalSubscription(eventName);
         this.memory.AddSubscription <T>(eventName, integrationEventHandler);
     }
     catch (EventBusException ex)
     {
         throw new EventBusException("Could not subscribe ", ex);
     }
 }
Exemplo n.º 8
0
        public async Task Subscribe <T>(string topicName, string subscriptionName, IIntegrationEventHandler <T> handler, int maxConcurrentCalls = 1)
            where T : IntegrationEvent
        {
            if (subscriptionName == null)
            {
                throw new ArgumentNullException(nameof(subscriptionName));
            }

            string key = GetSubscriptionKey(topicName, subscriptionName);

            if (_subscriptions.ContainsKey(key))
            {
                throw new ArgumentException($"Subscription {subscriptionName} for topic {topicName} already exist");
            }

            await _serviceBusPersistentConnection.CreateSubscriptionIfNotExists(topicName, subscriptionName);

            var client = new SubscriptionClient(_serviceBusPersistentConnection.ConnectionString, topicName, subscriptionName);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = maxConcurrentCalls,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };

            client.RegisterMessageHandler(async(message, token) =>
            {
                var model = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(message.Body));
                await handler.Handle(model);

                await client.CompleteAsync(message.SystemProperties.LockToken);
            }, messageHandlerOptions);

            _subscriptions.TryAdd(key, 0);
        }
Exemplo n.º 9
0
 public Task Handle(ProcessCompletedIntegrationEvent @event)
 {
     HandlerCalled = true;
     realHandler.Handle(@event)
 }