public async Task <IActionResult> CreateItemCategory([FromRoute(Name = "name")] string name)
        {
            var command = new CreateItemCategoryCommand(name);
            await commandDispatcher.DispatchAsync(command, default);

            return(Ok());
        }
 public async Task <ShoppingCart.Model.ShoppingCart> Get()
 {
     return(await _dispatcher.DispatchAsync(new GetCartQuery
     {
         UserId = this.GetUserId()
     }));
 }
        public async Task <ActionResult> AddItem([FromQuery] string name)
        {
            var newItemId = Guid.NewGuid();
            await _commandDispatcher.DispatchAsync(new CreateInventoryItemCommand(newItemId, name));

            return(StatusCode(201, newItemId.ToString()));
        }
        public override async Task <PersistResponse> Persist(PersistRequest request, ServerCallContext context)
        {
            try
            {
                await _commandDispatcher.DispatchAsync(new PersistNavigationCommand
                {
                    Id         = request.Id,
                    Navigation = request.Navigation,
                });

                return(new PersistResponse
                {
                    StatusCode = PersistResponse.Types.StatusCode.Ok,
                });
            }
            catch (ArgumentException e)
            {
                _logger.LogError($"Failed persisting entity {request.Id}", e);
                return(new PersistResponse
                {
                    StatusCode = PersistResponse.Types.StatusCode.Invalid,
                    Errors = { e.Message },
                });
            }
            catch (Exception e)
            {
                _logger.LogError($"Failed persisting entity {request.Id}", e);
            }

            return(new PersistResponse
            {
                StatusCode = PersistResponse.Types.StatusCode.Unavailable,
            });
        }
Example #5
0
 public async Task <Guid> AddTelegramAccount(string externalAccountId)
 {
     return(await _commandDispatcher.DispatchAsync <AddAccount.Request, AddAccount.Command>(new AddAccount.Request()
     {
         ExternalAccountId = externalAccountId
     }));
 }
Example #6
0
        public async Task <IHttpActionResult> Post([FromBody] CreatePlaylist command)
        {
            await _commandDispatcher.DispatchAsync(command);

            var playlist = await _playlistService.GetLatesAddedAsync();

            return(Created($"api/playlists/{command.Id}", playlist));
        }
        public async Task InvokeAsync()
        {
            var instanceWorkerId = _workerRecordStoreService.GenerateUniqueId();
            await _workerRecordStoreService.RecordPing("ingester", instanceWorkerId);

            var rawDataQueueMessages = await _queueClient.Dequeue(_config.RawDataQueueName, _config.MaxQueueItemsBatchSizeToProcessPerWorker);

            if (rawDataQueueMessages.Count == 0)
            {
                await _workerRecordStoreService.RecordHasTerminated("ingester", instanceWorkerId);

                return;
            }

            foreach (var rawDataQueueMessage in rawDataQueueMessages)
            {
                var    rawDataObjectKey    = rawDataQueueMessage.Message;
                Stream rawDataObjectStream = await _commandDispatcher.DispatchAsync(new RetrieveObjectCommand { Key = rawDataQueueMessage.Message });

                var objectName = _keyRegex.Match(rawDataObjectKey).Groups["objectName"].Value;

                using (var objectReader = new StreamReader(rawDataObjectStream))
                {
                    while (!objectReader.EndOfStream)
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var ingestedObjectKey = $"{_config.IngestedFolder}/{objectName}-{Guid.NewGuid()}";

                            using (var sw = new StreamWriter(memoryStream))
                            {
                                for (int i = 0; i < _config.IngesterMaxLinesPerFile && !objectReader.EndOfStream; i++)
                                {
                                    var line = await objectReader.ReadLineAsync();

                                    await sw.WriteLineAsync(line);
                                }

                                await sw.FlushAsync();

                                await _commandDispatcher.DispatchAsync(new StoreObjectCommand
                                {
                                    Key        = ingestedObjectKey,
                                    DataStream = memoryStream
                                });
                            }

                            await _queueClient.Enqueue(_config.IngestedQueueName, ingestedObjectKey);
                        }
                    }
                }

                await _queueClient.MessageProcessed(_config.RawDataQueueName, rawDataQueueMessage.MessageId);
            }

            await _workerRecordStoreService.RecordHasTerminated("ingester", instanceWorkerId);
        }
        public async Task <IActionResult> Worker(Guid id)
        {
            await _commandDispatcher.DispatchAsync(new DeleteWorker()
            {
                WorkerID = id
            });

            return(Ok());
        }
Example #9
0
        public async Task <IActionResult> CreateStore([FromBody] CreateStoreContract createStoreContract)
        {
            var model   = storeCreationInfoConverter.ToDomain(createStoreContract);
            var command = new CreateStoreCommand(model);

            await commandDispatcher.DispatchAsync(command, default);

            return(Ok());
        }
        public async Task <IActionResult> Worker([FromBody] WorkerDTO workerDTO)
        {
            await _commandDispatcher.DispatchAsync(new AddWorker()
            {
                Worker = workerDTO
            });

            return(Ok());
        }
Example #11
0
        public void DispatchAsync_InvoiceModelIsInvalid_CommandDispatcherDispatchMustNotHaveHappened()
        {
            A.CallTo(() => _validationProcessor.Validate(_command)).Returns(new ValidationStatus(new List <ValidationError> {
                new ValidationError("error")
            }));

            Assert.Throws <ValidationException>(() => _validatedCommandDispatcher.DispatchAsync(_command));

            A.CallTo(() => _commandDispatcher.DispatchAsync(A <ICommand> ._)).MustNotHaveHappened();
        }
        public async Task <IActionResult> Post()
        {
            var cmd = new CreateUserCommand(Guid.NewGuid(), "Nelson", "Junior", new DateTime(1989, 6, 9));

            await _dispatcher.DispatchAsync(cmd);

            await _unitOfWork.CommitAsync();

            return(Ok(cmd));
        }
        public async Task <IActionResult> Post()
        {
            var cmd = new CreateFooCommand(Guid.NewGuid());

            await _dispatcher.DispatchAsync(cmd);

            await _unitOfWork.CommitAsync();

            return(Ok(cmd));
        }
Example #14
0
        public async Task <IActionResult> Post()
        {
            var cmd = new CreateFooCommand(Guid.NewGuid());

            var response = await _dispatcher.DispatchAsync <CreateFooCommand, CreateFooResponse>(cmd);

            await _session.CommitAsync();

            return(Ok(cmd));
        }
Example #15
0
        public async Task <HttpResponseMessage> UpdateQuestion([FromBody] QuestionDto question)
        {
            var command = new UpdateQuestion(question);
            var result  = await _commandDispatcher.DispatchAsync(command) as IdentityResult;

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(result.Identity)
            });
        }
Example #16
0
        private async Task <IActionResult> RefreshToken(TokenRequestViewModel viewModel)
        {
            try
            {
                var refreshTokenResult = await _queryDispatcher.DispatchAsync <GetTokenQuery, GetTokenQueryResult>(new GetTokenQuery
                {
                    ClientId     = viewModel.ClientId,
                    RefreshToken = viewModel.RefreshToken
                });

                if (refreshTokenResult.Token == null)
                {
                    return(new UnauthorizedResult());
                }

                var userResult = await _queryDispatcher.DispatchAsync <GetUserByIdQuery, GetUserQueryResult>(new GetUserByIdQuery
                {
                    UserId = refreshTokenResult.Token.UserId
                });

                if (userResult.User == null)
                {
                    return(new UnauthorizedResult());
                }

                var newRefreshToken = _tokenService.GenerateRefreshToken(refreshTokenResult.Token.ClientId,
                                                                         refreshTokenResult.Token.UserId);

                await _commandDispatcher.DispatchAsync <RemoveTokenCommand>(new RemoveTokenCommand
                {
                    Id = refreshTokenResult.Token.Id
                });

                await _commandDispatcher.DispatchAsync <AddTokenCommand>(new AddTokenCommand
                {
                    Token = refreshTokenResult.Token
                });

                var tokenData = _tokenService.CreateAccessToken(newRefreshToken.UserId);

                var response = new TokenResponseViewModel
                {
                    Expiration   = tokenData.ExporationTimeInMinutes,
                    RefreshToken = newRefreshToken.Value,
                    Token        = tokenData.EncodedToken
                };

                return(Json(response));
            }
            catch (Exception)
            {
                return(new UnauthorizedResult());
            }
        }
Example #17
0
        public async Task ProcessMessageAsync(GatewayPayload payload)
        {
            var message = JsonConvert.DeserializeObject <GatewayMessage>(payload.EventData.ToString());

            if (_commandValidator.IsCommand(message))
            {
                var command = new Command(message);

                await _commandDispatcher.DispatchAsync(command);
            }
        }
Example #18
0
        public async Task <IActionResult> Login([FromBody] UserLoginDTO userParam)
        {
            var command = new Login()
            {
                LoginCredentials = userParam
            };

            await _commandDispatcher.DispatchAsync(command);

            return(new JsonResult(command.Token));
        }
Example #19
0
        protected async Task <IActionResult> DispatchCommandAsync <T>(T command) where T : ICommand
        {
            var result = await _commandDispatcher.DispatchAsync(command, User);

            if (!result.IsSuccess)
            {
                return(BadRequest(result));
            }

            return(Accepted(result));
        }
Example #20
0
        public async Task <Guid> CriarAsync(CriarProdutoDto dto)
        {
            var produtoId = Guid.NewGuid();
            var command   = new CriarProdutoCommand(produtoId, dto.Codigo, dto.Nome, dto.Preco, dto.Quantidade);

            await _dispatcher.DispatchAsync(command);

            await _unitOfWork.CommitAsync();

            return(produtoId);
        }
Example #21
0
        private bool ProcessCommand(string command)
        {
            try
            {
                AppHealth.Current.Verbose.TrackAsync(string.Format(StringRes.ReceivedCommand, command)).FireAndForget();

                var args = Regex.Split(command, splitPattern)
                           .Select(s => s.Trim('"'));

                var parserResult = _parser.ParseArguments <
                    SyncCommand,
                    GetProjectTypesCommand,
                    GetFrameworksCommand,
                    GetLayoutsCommand,
                    GetPagesCommand,
                    GetFeaturesCommand,
                    GetServicesCommand,
                    GetTestingsCommand,
                    GetAllLicencesCommand,
                    GenerateCommand,
                    CloseCommand>(args);

                var exitCode = parserResult.MapResult(
                    (SyncCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetProjectTypesCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetFrameworksCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetLayoutsCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetPagesCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetFeaturesCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetServicesCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetTestingsCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GetAllLicencesCommand opts) => _dispatcher.DispatchAsync(opts),
                    (GenerateCommand opts) => _dispatcher.DispatchAsync(opts),
                    (CloseCommand opts) => Task.FromResult(1),
                    errors =>
                {
                    var helpText  = HelpText.AutoBuild(parserResult);
                    var errorText = string.Format(StringRes.ErrorParsingCommand, command, helpText);
                    _messageService.SendError(errorText);
                    AppHealth.Current.Error.TrackAsync(errorText).FireAndForget();
                    return(Task.FromResult(0));
                });

                // todo: use async task
                return(exitCode.Result == 0);
            }
            catch (Exception ex)
            {
                var errorMessage = string.Format(StringRes.ErrorExecutingCommand, command, ex.Message);
                AppHealth.Current.Exception.TrackAsync(ex, errorMessage).FireAndForget();
                _messageService.SendError(errorMessage);
                return(true);
            }
        }
        public async Task <IActionResult> Create(string username, string password, string email)
        {
            await _commandDispatcher.DispatchAsync(new CreateUserCommand
            {
                CreateProfile = true,
                Email         = email,
                Password      = password,
                UserName      = username,
            }, HttpContext.RequestAborted);

            return(Ok());
        }
Example #23
0
        public async Task <IActionResult> Create([FromBody] CreateBoardRequestDTO dto)
        {
            var command = new CreateBoardCommandHandler.Command
            {
                UserId         = GetUser().ID,
                Name           = dto.Name,
                ParticipantIds = dto.ParticipantIds
            };
            await _commandDispatcher.DispatchAsync(command);

            return(Json(new ApiJsonResponse(command.BoardId, ApiMessage.Info($"'{dto.Name}' board has been created"))));
        }
        public async Task <IActionResult> AddByClient([FromBody] ClientOrderDTO clOrder)
        {
            var command = new AddClientOrder()
            {
                Order = clOrder,
                User  = User
            };


            await _commandDispatcher.DispatchAsync(command);

            return(Ok());
        }
        public static async Task Run()
        {
            ICommandDispatcher   dispatcher = Configure();
            CommandWithoutResult command    = new CommandWithoutResult
            {
                DoSomething = "Hello"
            };
            await dispatcher.DispatchAsync(command);

            await dispatcher.DispatchAsync(command);

            Console.WriteLine("\nPress a key to continue...");
        }
        public async Task <IActionResult> Add(AddCommentRequestDTO dto)
        {
            await _commandDispatcher.DispatchAsync(
                new AddCommandHandler.Command
            {
                BoardId = dto.BoardId,
                Content = dto.Content,
                UserId  = GetUser().ID,
                ItemId  = dto.ItemId
            });

            return(await GetComments(dto.ItemId));
        }
        public async Task <IActionResult> Post()
        {
            CommandResponse <Order> response = await _dispatcher.DispatchAsync(new CreateOrderCommand
            {
                UserId = this.GetUserId()
            });

            if (response.IsSuccess)
            {
                return(Ok(response.Result));
            }
            return(BadRequest(response.ErrorMessage));
        }
Example #28
0
        private async Task <string> UpdateRefreshTokenAsync(string userName, HttpContext httpContext)
        {
            string?newRefreshToken = null;

            await _commandDispatcher.DispatchAsync(new UpdateJwtRefreshTokenCommand
            {
                UserName = userName,
                TokenExpirationTimeSpan = _jwtRefreshTokenExpirationTime,
                Verify         = false,
                OnKeyGenerated = (_, key) => newRefreshToken = (string)key
            }, httpContext.RequestAborted);

            return(newRefreshToken ?? throw new InvalidOperationException());
        }
        public static async Task Run()
        {
            ICommandDispatcher     dispatcher = Configure();
            OutputToConsoleCommand command    = new OutputToConsoleCommand
            {
                Message = "Hello"
            };
            CountResult result = await dispatcher.DispatchAsync(command);

            Console.WriteLine($"{result.Count} actors called");
            await dispatcher.DispatchAsync(command);

            Console.WriteLine("\nPress a key to continue...");
        }
Example #30
0
        public async Task ShouldNotRecheduleCommandThatReturnsFalse()
        {
            // Arrange
            _registrationCatalogue.GetRegisteredCommands().Returns(new Type[] { typeof(SimpleSchedulableCommand) });
            SimpleSchedulableCommand command = new SimpleSchedulableCommand();

            _commandDispatcher.DispatchAsync(command).ReturnsForAnyArgs(new CommandResult <bool>(false, false));

            // Act
            await _testSubject.ExecuteAsync(new SimpleSchedulableCommand().CreateScheduledMessage());

            // Assert
            await _commandRescheduler.DidNotReceiveWithAnyArgs().Reschedule(null);
        }