예제 #1
0
        public async Task <IActionResult> SendMessage()
        {
            var greetingAsync = new GreetingAsyncEvent("Hello from the web");
            var greeting      = new GreetingEvent("Hello from the web");

            _context.Greetings.Add(greeting);
            _context.GreetingsAsync.Add(greetingAsync);

            await _context.SaveChangesAsync();

            _commandProcessor.Post(greeting);
            await _commandProcessor.PostAsync(greetingAsync);

            return(View("Index"));
        }
예제 #2
0
            public async Task StartAsync(CancellationToken cancellationToken)
            {
                long loop = 0;

                while (true)
                {
                    try
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        loop++;

                        Console.WriteLine($"Sending message #{loop}");
                        _commandProcessor.Post(new GreetingEvent($"Ian #{loop}"));

                        if (loop % 100 != 0)
                        {
                            continue;
                        }

                        Console.WriteLine("Pausing for breath...");
                        await Task.Delay(4000, cancellationToken);
                    }
                    catch (BrokenCircuitException)
                    {
                        Console.WriteLine("Can't send to producer, pausing...will retry in 5 seconds");
                        Task.Delay(TimeSpan.FromSeconds(5)).Wait();
                    }
                }
            }
예제 #3
0
            public async Task StartAsync(CancellationToken cancellationToken)
            {
                long loop = 0;

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    loop++;

                    Console.WriteLine($"Sending message #{loop}");
                    _commandProcessor.Post(new GreetingEvent($"Ian #{loop}"));

                    if (loop % 100 != 0)
                    {
                        continue;
                    }

                    Console.WriteLine("Pausing for breath...");
                    await Task.Delay(4000, cancellationToken);
                }
            }
        public override HelloWorldCommand Handle(HelloWorldCommand command)
        {
            _logger.Information($"Handling HelloWorldCommand {command.Id}");
            _logger.Information(command.Message);

            _commandProcessor.Post(new ProcessMessageCommand(command.Message));

            return(base.Handle(command));
        }
예제 #5
0
        public void ProcessRecord(StreamRecord streamRecord)
        {
            IRecordTranslator <StreamRecord, AccountEvent> translator = _translatorRegistry.Get <StreamRecord, AccountEvent>();
            var accountEvent = translator.TranslateFromRecord(streamRecord);

            _commandProcessor.Post(accountEvent);

            _logger.LogDebug($"Process Record {streamRecord.SequenceNumber}");
        }
        public void When_completing_a_missing_task()
        {
            _exception = Catch.Exception(() => _handler.Handle(_cmd));

            //_should_fail
            Assert.IsInstanceOf <ArgumentOutOfRangeException>(_exception);
            //_should_not_post_event
            A.CallTo(() => _commandProcessor.Post(A <TaskCompletedEvent> ._)).MustNotHaveHappened();
        }
예제 #7
0
        public IActionResult Post([FromBody] BulkAddToDoRequest request)
        {
            var bulkAddCommand = new BulkAddToDoCommand(request.ItemsToAdd);

            _commandProcessor.Post(bulkAddCommand);

            //TODO: Should have a monitoring endpoint, and share a job table location for tracking progress
            return(Accepted());
        }
예제 #8
0
        public void When_completing_an_existing_task()
        {
            _handler.Handle(_cmd);
            _taskToBeCompleted = _tasksDAO.FindById(_cmd.TaskId);

            //_should_update_the_tasks_completed_date
            Assert.AreEqual(s_COMPLETION_DATE.Date, _taskToBeCompleted.CompletionDate.Value.Date);
            //_should_post_event
            A.CallTo(() => s_commandProcessor.Post(A <TaskCompletedEvent> ._)).MustHaveHappened(Repeated.Exactly.Once);
        }
        /// <summary>
        /// We want to send a heartbeat back to the caller. The heartbeat consists of the set of channels we own
        /// and their current status.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns>TRequest.</returns>
        public override HeartbeatRequest Handle(HeartbeatRequest command)
        {
            var heartbeat = new HeartbeatReply(_dispatcher.HostName, new ReplyAddress(command.ReplyAddress.Topic, command.ReplyAddress.CorrelationId));

            _dispatcher.Consumers.Each((consumer) => heartbeat.Consumers.Add(new RunningConsumer(consumer.Name, consumer.State)));

            _commandProcessor.Post(heartbeat);

            return(base.Handle(command));
        }
예제 #10
0
        public override GreetingEvent Handle(GreetingEvent @event)
        {
            Console.WriteLine("Received Greeting. Message Follows");
            Console.WriteLine("----------------------------------");
            Console.WriteLine(@event.Greeting);
            Console.WriteLine("----------------------------------");
            Console.WriteLine("Message Ends");

            _commandProcessor.Post(new GreetingAsyncEvent("Greetings from Non Async"));

            return(base.Handle(@event));
        }
예제 #11
0
        private void DoWork(object state)
        {
            _iteration++;

            var greetingEvent = new GreetingEvent {
                Id = Guid.NewGuid(), Greeting = $"Hello # {_iteration}"
            };

            _processor.Post(greetingEvent);

            _logger.LogInformation($"Sending message with id {greetingEvent.Id} and greeting {greetingEvent.Greeting}");
        }
        public void Establish()
        {
            _tasksDAO = new Tasks.Adapters.DataAccess.TasksDAO();
            _tasksDAO.Clear();
            _cmd = new CompleteTaskCommand(TASK_ID, _COMPLETION_DATE);

            _commandProcessor = A.Fake <IAmACommandProcessor>();

            A.CallTo(() => _commandProcessor.Post(A <TaskCompletedEvent> ._));

            _handler = new CompleteTaskCommandHandler(_tasksDAO, _commandProcessor);
        }
예제 #13
0
        public override TaskReminderCommand Handle(TaskReminderCommand taskReminderCommand)
        {
            //_mailGateway.Send(new TaskReminder(
            //    taskName: new TaskName(taskReminderCommand.TaskName),
            //    dueDate: taskReminderCommand.DueDate,
            //    reminderTo: new EmailAddress(taskReminderCommand.Recipient),
            //    copyReminderTo: new EmailAddress(taskReminderCommand.CopyTo)
            //    ));

            _commandProcessor.Post(new TaskReminderSentEvent(taskReminderCommand.Id, taskReminderCommand.TaskId, taskReminderCommand.TaskName, taskReminderCommand.DueDate, taskReminderCommand.Recipient, taskReminderCommand.CopyTo));

            return(base.Handle(taskReminderCommand));
        }
예제 #14
0
        public IActionResult Post([FromBody] TaskReminderModel reminder)
        {
            var reminderCommand = new TaskReminderCommand(
                taskId: reminder.TaskId,
                taskName: reminder.TaskName,
                dueDate: DateTime.Parse(reminder.DueDate),
                recipient: reminder.Recipient,
                copyTo: reminder.CopyTo
                );

            _commandProcessor.Post(reminderCommand);

            return(new StatusCodeResult(202));
        }
예제 #15
0
        public override EditTaskCommand Handle(EditTaskCommand editTaskCommand)
        {
            var task = _tasksDAO.FindById(editTaskCommand.TaskId);

            task.TaskName        = editTaskCommand.TaskName;
            task.TaskDescription = editTaskCommand.TaskDescription;
            task.DueDate         = editTaskCommand.TaskDueDate;

            _tasksDAO.Update(task);

            _commandProcessor.Post(new TaskEditedEvent(editTaskCommand.Id, editTaskCommand.TaskId, editTaskCommand.TaskName, editTaskCommand.TaskDescription, editTaskCommand.TaskDueDate));

            return(base.Handle(editTaskCommand));
        }
        public void When_editing_an_existing_task()
        {
            _handler.Handle(_cmd);
            _taskToBeEdited = _tasksDAO.FindById(_cmd.TaskId);

            //_should_update_the_task_with_the_new_task_name
            Assert.AreEqual(NEW_TASK_NAME, _taskToBeEdited.TaskName);
            //_should_update_the_task_with_the_new_task_description
            Assert.AreEqual(NEW_TASK_DESCRIPTION, _taskToBeEdited.TaskDescription);
            //_should_update_the_task_with_the_new_task_time
            Assert.AreEqual(_NEW_TIME.Date, _taskToBeEdited.DueDate.Value.Date);
            //_should_post_event
            A.CallTo(() => s_commandProcessor.Post(A <TaskEditedEvent> ._)).MustHaveHappened(Repeated.Exactly.Once);
        }
예제 #17
0
        public OperationResult Post(TaskReminderModel reminder)
        {
            var reminderCommand = new TaskReminderCommand(
                taskName: reminder.TaskName,
                dueDate: DateTime.Parse(reminder.DueDate),
                recipient: reminder.Recipient,
                copyTo: reminder.CopyTo
                );

            commandProcessor.Post(reminderCommand);

            return(new OperationResult.OK()
            {
                StatusCode = (int)HttpStatusCode.Accepted
            });
        }
예제 #18
0
        public override AddTaskCommand Handle(AddTaskCommand addTaskCommand)
        {
            var inserted = _tasksDAO.Add(
                new Task(
                    taskName: addTaskCommand.TaskName,
                    taskDecription: addTaskCommand.TaskDescription,
                    dueDate: addTaskCommand.TaskDueDate
                    )
                );

            addTaskCommand.TaskId = inserted.Id;

            _commandProcessor.Post(new TaskAddedEvent(addTaskCommand.Id, addTaskCommand.TaskId, addTaskCommand.TaskName, addTaskCommand.TaskDescription, addTaskCommand.TaskDueDate));

            return(base.Handle(addTaskCommand));
        }
예제 #19
0
        public override async Task <AddToDoCommand> HandleAsync(AddToDoCommand command, CancellationToken cancellationToken = new CancellationToken())
        {
            using (var uow = new ToDoContext(_options))
            {
                var repository = new ToDoItemRepositoryAsync(uow);
                var savedItem  = await repository.AddAsync(
                    new ToDoItem { Title = command.Title, Completed = command.Commpleted, Order = command.Order },
                    cancellationToken
                    );

                command.ToDoItemId = savedItem.Id;
            }

            _commandProcessor.Post(new TaskCreatedEvent(command.Title));
            return(await base.HandleAsync(command, cancellationToken));
        }
예제 #20
0
        public override EditTaskCommand Handle(EditTaskCommand editTaskCommand)
        {
            using (var scope = _tasksDAO.BeginTransaction())
            {
                Task task = _tasksDAO.FindById(editTaskCommand.TaskId);

                task.TaskName        = editTaskCommand.TaskName;
                task.TaskDescription = editTaskCommand.TaskDescription;
                task.DueDate         = editTaskCommand.TaskDueDate;

                _tasksDAO.Update(task);
                scope.Commit();
            }

            _commandProcessor.Post(new TaskEditedEvent(editTaskCommand.Id, editTaskCommand.TaskId, editTaskCommand.TaskName, editTaskCommand.TaskDescription, editTaskCommand.TaskDueDate));

            return(base.Handle(editTaskCommand));
        }
예제 #21
0
        public override CompleteTaskCommand Handle(CompleteTaskCommand completeTaskCommand)
        {
            var task = _tasksDAO.FindById(completeTaskCommand.TaskId);

            if (task != null)
            {
                task.CompletionDate = completeTaskCommand.CompletionDate;
                _tasksDAO.Update(task);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(completeTaskCommand), completeTaskCommand, "Could not find the task to complete");
            }

            _commandProcessor.Post(new TaskCompletedEvent(completeTaskCommand.Id, completeTaskCommand.TaskId, completeTaskCommand.CompletionDate));

            return(base.Handle(completeTaskCommand));
        }
예제 #22
0
            public async Task StartAsync(CancellationToken cancellationToken)
            {
                using (new TransactionScope(TransactionScopeOption.RequiresNew,
                                            new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                                            TransactionScopeAsyncFlowOption.Enabled))
                {
                    Console.WriteLine($"Sending {_repeatCount} command messages");
                    var sequenceNumber = 1;
                    for (int i = 0; i < _repeatCount; i++)
                    {
                        _commandProcessor.Post(new CompetingConsumerCommand(sequenceNumber++));
                    }
                    // We do NOT complete the transaction here to show that a message is
                    // always queued, whether the transaction commits or aborts!
                }

                await Task.CompletedTask;
            }
예제 #23
0
        private void DoWork(object state)
        {
            _iteration++;

            var greetingEvent = new GreetingEvent {
                Id = Guid.NewGuid(), Greeting = $"Hello # {_iteration}"
            };

            try
            {
                _processor.Post(greetingEvent);
            }
            catch (Exception e)
            {
                _logger.LogError($"Kafka Message Generator is stopping due to {e.Message}");
                _appLifetime.StopApplication();
            }

            _logger.LogInformation($"Sending message with id {greetingEvent.Id} and greeting {greetingEvent.Greeting}");
        }
예제 #24
0
        public override AddTaskCommand Handle(AddTaskCommand addTaskCommand)
        {
            using (var scope = _tasksDAO.BeginTransaction())
            {
                var inserted = _tasksDAO.Add(
                    new Task(
                        taskName: addTaskCommand.TaskName,
                        taskDecription: addTaskCommand.TaskDescription,
                        dueDate: addTaskCommand.TaskDueDate
                        )
                    );

                scope.Commit();

                addTaskCommand.TaskId = inserted.Id;
            }

            _commandProcessor.Post(new TaskAddedEvent(addTaskCommand.Id, addTaskCommand.TaskId, addTaskCommand.TaskName, addTaskCommand.TaskDescription, addTaskCommand.TaskDueDate));

            return(base.Handle(addTaskCommand));
        }
예제 #25
0
        public override CompleteTaskCommand Handle(CompleteTaskCommand completeTaskCommand)
        {
            using (var scope = _tasksDAO.BeginTransaction())
            {
                Task task = _tasksDAO.FindById(completeTaskCommand.TaskId);
                if (task != null)
                {
                    task.CompletionDate = completeTaskCommand.CompletionDate;
                    _tasksDAO.Update(task);
                    scope.Commit();
                }
                else
                {
                    throw new ArgumentOutOfRangeException("completeTaskCommand", completeTaskCommand, "Could not find the task to complete");
                }
            }

            _commandProcessor.Post(new TaskCompletedEvent(completeTaskCommand.Id, completeTaskCommand.TaskId, completeTaskCommand.CompletionDate));

            return(base.Handle(completeTaskCommand));
        }
예제 #26
0
        public override GreetingRequest Handle(GreetingRequest request)
        {
            string salutation;

            switch (request.Language)
            {
            case ("en-gb"):
            case ("en-us"):
                salutation = "Hello";
                break;

            case ("fr-fr"):
                salutation = "Bonjour";
                break;

            case ("de-de"):
                salutation = "Hallo";
                break;

            case ("tlh"):
                salutation = "nuqneH";
                break;

            default:
                salutation = "Salution";
                break;
            }

            salutation += " " + request.Name;

            var response = new GreetingReply(request.ReplyAddress)
            {
                Salutation = salutation
            };

            _commandProcessor.Post(response);

            return(base.Handle(request));
        }
        public override async Task <UpdateToDoCommand> HandleAsync(UpdateToDoCommand command,
                                                                   CancellationToken cancellationToken = new CancellationToken())
        {
            string title;

            using (var uow = new ToDoContext(_options))
            {
                var repository = new ToDoItemRepositoryAsync(uow);
                var toDoItem   = await repository.GetAsync(command.ToDoId, cancellationToken);

                if (command.Title != null)
                {
                    toDoItem.Title = command.Title;
                }

                if (command.Complete.HasValue)
                {
                    toDoItem.Completed = command.Complete.Value;
                }

                if (command.Order.HasValue)
                {
                    toDoItem.Order = command.Order.Value;
                }

                await repository.UpdateAsync(toDoItem, cancellationToken);

                title = toDoItem.Title;
            }

            if (command.Complete.HasValue && command.Complete.Value)
            {
                var taskCompleteEvent = new TaskCompletedEvent(title);

                _commandProcessor.Post(taskCompleteEvent);
            }

            return(await base.HandleAsync(command, cancellationToken));
        }
예제 #28
0
        public override GreetingRequest Handle(GreetingRequest request)
        {
            var salutation = request.Language switch
            {
                ("en-gb") => "Hello",
                ("en-us") => "Hello",
                ("fr-fr") => "Bonjour",
                ("de-de") => "Hallo",
                ("tlh") => "nuqneH",
                _ => "Salution"
            };

            salutation += " " + request.Name;

            var response = new GreetingReply(request.ReplyAddress)
            {
                Salutation = salutation
            };

            _commandProcessor.Post(response);

            return(base.Handle(request));
        }
예제 #29
0
 public override AddOrderCommand Handle(AddOrderCommand addOrderCommand)
 {
     _commandProcessor.Post(addOrderCommand);
     return(base.Handle(addOrderCommand));
 }
예제 #30
0
 public void Post <T>(T request)
     where T : class, IRequest
 {
     _commandProcessor.Post(request);
 }