Ejemplo n.º 1
0
        public async Task HandleAsync(CreateUser command)
        {
            _logger.LogInformation("Create user: {User} with email {Email}",
                                   command.Name, command.Email);

            try
            {
                await _userService.RegisterAsync(command.Email, command.Password, command.Name);

                await _bus.PublishAsync(new UserCreated(command.Email, command.Name));
            }
            catch (ActioException ex)
            {
                _logger.LogError(ex, ex.Message);
                await _bus.PublishAsync(new CreateUserRejected(command.Email, ex.Code, ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await _bus.PublishAsync(new CreateUserRejected(command.Email, "error", ex.Message));
            }
        }
        public async Task HandleAsync(CreateActivity Command)
        {
            _logger.LogInformation($"Creating Activity: {Command.Name} !");
            try
            {
                await _activityService.AddAsync(Command.Id, Command.UserId, Command.Category, Command.Name, Command.Description, Command.CreatedAt);

                await _busClient.PublishAsync(new ActivityCreated(Command.Id, Command.UserId, Command.Category, Command.Name, Command.Description, Command.CreatedAt));
            }
            catch (ActioException ex)
            {
                await _busClient.PublishAsync(new CreateActivityRejected(Command.Id, ex.Message, ex.Code));

                _logger.LogError(ex.Message);
            }
            catch (Exception ex)
            {
                await _busClient.PublishAsync(new CreateActivityRejected(Command.Id, ex.Message, "error"));

                _logger.LogError(ex.Message);
            }
        }
Ejemplo n.º 3
0
 public async Task HandleAsync(CreateMovie command)
 {
     Console.WriteLine($"Creating movie {command.Title}");
     try
     {
         await movieService.AddAsync(command.Url, command.Title, command.Duration, command.Description);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     await busClient.PublishAsync(new MovieCreated(command.Id, command.Title));
 }
Ejemplo n.º 4
0
        public async Task <IActionResult> Post([FromBody] CreateMovie createMovie)
        {
            try
            {
                await busClient.PublishAsync(createMovie);

                return(Accepted($"api/movies/{createMovie.Id}"));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Post(int number)
        {
            int?result = _repo.Get(number);

            if (!result.HasValue)
            {
                await _client.PublishAsync(new CalculateValueCommand()
                {
                    Number = number
                });
            }
            return(Accepted($"fib/{number}", null));
        }
Ejemplo n.º 6
0
 public async Task HandleAsync(RenewRemark command)
 {
     await _handler
     .Validate(async() =>
     {
         var remark = await _remarkService.GetAsync(command.RemarkId);
         if (remark.Value.Group == null)
         {
             return;
         }
         await _groupService.ValidateIfRemarkCanBeRenewedOrFailAsync(remark.Value.Group.Id, command.UserId);
     })
     .Run(async() =>
     {
         Location location = null;
         if (command.Latitude != 0 && command.Longitude != 0)
         {
             location = Location.Create(command.Latitude, command.Longitude, command.Address);
         }
         await _remarkStateService.RenewAsync(command.RemarkId, command.UserId, command.Description, location);
     })
     .OnSuccess(async() =>
     {
         var remark   = await _remarkService.GetAsync(command.RemarkId);
         var state    = remark.Value.GetLatestStateOf(RemarkState.Names.Renewed).Value;
         var resource = _resourceFactory.Resolve <RemarkRenewed>(command.RemarkId);
         await _bus.PublishAsync(new RemarkRenewed(command.Request.Id, resource,
                                                   command.UserId, command.RemarkId));
     })
     .OnCustomError(async ex => await _bus.PublishAsync(new RenewRemarkRejected(command.Request.Id,
                                                                                command.UserId, command.RemarkId, ex.Code, ex.Message)))
     .OnError(async(ex, logger) =>
     {
         logger.Error(ex, "Error occured while renewing a remark.");
         await _bus.PublishAsync(new RenewRemarkRejected(command.Request.Id,
                                                         command.UserId, command.RemarkId, OperationCodes.Error, ex.Message));
     })
     .ExecuteAsync();
 }
Ejemplo n.º 7
0
 public async Task HandleAsync(ActivateAccount command)
 {
     await _handler
     .Run(async() => await _userService
          .ActivateAsync(command.Email, command.Token))
     .OnSuccess(async() =>
     {
         var user = await _userService.GetByEmailAsync(command.Email, Providers.Collectively);
         await _bus
         .PublishAsync(new AccountActivated(command.Request.Id, command.Email, user.Value.UserId));
     })
     .OnCustomError(async ex => await _bus
                    .PublishAsync(new ActivateAccountRejected(command.Request.Id,
                                                              command.Email, ex.Code, ex.Message)))
     .OnError(async(ex, logger) =>
     {
         logger.Error(ex, "Error when activating account.");
         await _bus.PublishAsync(new ActivateAccountRejected(command.Request.Id,
                                                             command.Email, OperationCodes.Error, "Error when activating account"));
     })
     .ExecuteAsync();
 }
Ejemplo n.º 8
0
        public async Task Handle(NotaFiscalCreatedDomainEvent notification, CancellationToken cancellationToken)
        {
            var message = new DespesaCreatedMessage
            {
                CPF    = notification.NotaFiscal.Periodo.DeputadoFederal.CPF,
                TipoId = 1,
                Ano    = notification.NotaFiscal.Periodo.Ano,
                Mes    = notification.NotaFiscal.Periodo.Mes,
                Valor  = notification.NotaFiscal.ValorDocumento
            };

            await _busClient.PublishAsync(message);
        }
Ejemplo n.º 9
0
        public async Task HandleAsync(CreateUser command)
        {
            _logger.LogInformation($"Create USer Handler called with params: User Email as {command.Email} and User Name as {command.Name}");
            try
            {
                await _userService.RegisterAsync(command.Email, command.Password, command.Name);

                await _busClient.PublishAsync(new UserCreated(command.Email, command.Name));

                _logger.LogInformation($"User created with Email {command.Email} and name {command.Name}");
            }
            catch (LearnException learnEx)
            {
                _logger.LogError(learnEx, learnEx.Message);
                await _busClient.PublishAsync(new CreateUserRejected(learnEx.Message, learnEx.Code, command.Email));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await _busClient.PublishAsync(new CreateUserRejected(ex.Message, "error", command.Email));
            }
        }
 public async Task HandleAsync(ProcessWardenCheckResult command)
 {
     CheckResult checkResult = null;
     await _handler
     .Run(async() => {
         checkResult = _wardenCheckService.ValidateAndParseResult(command.UserId,
                                                                  command.OrganizationId, command.WardenId, command.Check);
         await _wardenCheckService.SaveAsync(checkResult);
     })
     .OnSuccess(async() => await _bus.PublishAsync(new WardenCheckResultProcessed(command.Request.Id,
                                                                                  command.UserId, command.OrganizationId, command.WardenId,
                                                                                  _mapper.Map <CheckResult, CheckResultDto>(checkResult))))
     .OnCustomError(async ex => await _bus.PublishAsync(new ProcessWardenCheckResultRejected(command.Request.Id,
                                                                                             command.UserId, ex.Code, ex.Message)))
     .OnError(async(ex, logger) =>
     {
         logger.Error("Error occured while processing Warden check result.");
         await _bus.PublishAsync(new ProcessWardenCheckResultRejected(command.Request.Id,
                                                                      command.UserId, OperationCodes.Error, ex.Message));
     })
     .ExecuteAsync();
 }
Ejemplo n.º 11
0
        private async Task DatabaseSpaceMetricCollect(DbWorkerOperationCompleted command)
        {
            var databaseSpaceMetrics = new DatabaseSpaceMetricsModel();
            var flatResult           = command.Result.SelectMany(x => x).Where(x => x.Key == "database_size" || x.Key == "unallocated space");
            var databaseSize         = flatResult.FirstOrDefault(x => x.Key == "database_size").Value.Split();

            databaseSpaceMetrics.DatabaseId       = command.DatabaseId;
            databaseSpaceMetrics.Space            = Convert.ToDouble(flatResult.FirstOrDefault(x => x.Key == "database_size").Value.Split()[0]);
            databaseSpaceMetrics.UnallocatedSpace = Convert.ToDouble(flatResult.FirstOrDefault(x => x.Key == "unallocated space").Value.Split()[0]);
            databaseSpaceMetrics.Unit             = "MB";

            await _databaseSpaceMetricsService.CreateAsync(databaseSpaceMetrics);

            await _busClient.PublishAsync(new DatabaseSpaceUsageMetricsCompleted(
                                              command.Id,
                                              command.UserId,
                                              databaseSpaceMetrics.DatabaseId,
                                              databaseSpaceMetrics.Space,
                                              databaseSpaceMetrics.UnallocatedSpace,
                                              databaseSpaceMetrics.Unit
                                              ));
        }
Ejemplo n.º 12
0
 public async Task HandleAsync(EditRemark command)
 => await _handler
 .Validate(async() =>
           await _remarkService.ValidateEditorAccessOrFailAsync(command.RemarkId, command.UserId))
 .Run(async() =>
 {
     Location location = null;
     if (command.Latitude.HasValue && command.Latitude != 0 &&
         command.Longitude.HasValue && command.Longitude != 0)
     {
         var locations = await _locationService.GetAsync(command.Latitude.Value, command.Longitude.Value);
         if (locations.HasNoValue || locations.Value.Results == null || !locations.Value.Results.Any())
         {
             throw new ServiceException(OperationCodes.AddressNotFound,
                                        $"Address was not found for remark with id: '{command.RemarkId}' " +
                                        $"latitude: {command.Latitude}, longitude:  {command.Longitude}.");
         }
         var address = locations.Value.Results.First().FormattedAddress;
         location    = Domain.Location.Create(command.Latitude.Value, command.Longitude.Value, address);
     }
     await _remarkService.EditAsync(command.RemarkId, command.UserId,
                                    command.GroupId, command.Category, command.Description, location);
 })
 .OnSuccess(async() =>
 {
     var remark   = await _remarkService.GetAsync(command.RemarkId);
     var resource = _resourceFactory.Resolve <RemarkEdited>(command.RemarkId);
     await _bus.PublishAsync(new RemarkEdited(command.Request.Id, resource,
                                              command.UserId, command.RemarkId));
 })
 .OnCustomError(async ex => await _bus.PublishAsync(new EditRemarkRejected(command.Request.Id,
                                                                           command.UserId, command.RemarkId, ex.Code, ex.Message)))
 .OnError(async(ex, logger) =>
 {
     logger.Error(ex, "Error occured while editing a remark.");
     await _bus.PublishAsync(new EditRemarkRejected(command.Request.Id,
                                                    command.UserId, command.RemarkId, OperationCodes.Error, ex.Message));
 })
 .ExecuteAsync();
        public async Task <IActionResult> Post(int n)
        {
            ulong?result = _repository.Get(n);

            if (!result.HasValue)
            {
                await _client.PublishAsync(new CalculateFactorial {
                    Number = n
                });
            }

            return(Accepted($"factorial/{n}", null));
        }
Ejemplo n.º 14
0
        public async Task HandlerAsync(CreateActivity command)
        {
            Console.WriteLine($"Receive Create Activity command:{command.Name}");
            try
            {
                await _activityService.AddAsync(command.Id, command.Name, command.Description,
                                                command.Category, command.UserId, command.CreatedAt);

                await _bus.PublishAsync(new ActivityCreated(command.Id, command.UserId, command.Category,
                                                            command.Name, command.Description));

                return;
            }
            catch (ActioException ex)
            {
                await _bus.PublishAsync(new CreateActivtyRejected(ex.Code, ex.Message));
            }
            catch (Exception ex)
            {
                await _bus.PublishAsync(new CreateActivtyRejected("error", ex.Message));
            }
        }
        public async Task HandleAsync(UserCreated @event)
        {
            try
            {
                var merchant = new Merchant();
                merchant.UserId        = @event.UserId;
                merchant.Name          = @event.Name;
                merchant.AcquiringBank = @event.AcquirerName;

                await _merchantRepository.AddAsync(merchant);

                var logCreated = new CreateLog(@event.UserId, Guid.Empty, LogLevel.Info, "Merchant_Created",
                                               "Created merchant " + @event.Name);
                await _busClient.PublishAsync(logCreated);
            }
            catch (Exception ex)
            {
                var logCreated = new CreateLog(@event.UserId, Guid.Empty, LogLevel.Error, "Merchant_Creation_Error",
                                               "Cannot save Merchant  because :" + ex.Message);
                await _busClient.PublishAsync(logCreated);
            }
        }
Ejemplo n.º 16
0
        public async Task HandleAsync(CreateUser command)
        {
            _logger.LogInformation($"Creating User: {command.Name}");
            try
            {
                await _userService.RegisterAsync(command.Email, command.Password, command.Name);

                await _busClient.PublishAsync(new UserCreated(command.Email, command.Name));
            }
            catch (JKTechException e)
            {
                await _busClient.PublishAsync(new CreateUserRejected(command.Email, e.Code, e.Message));

                _logger.LogError(e.Message);
            }
            catch (Exception ex)
            {
                await _busClient.PublishAsync(new CreateUserRejected(command.Email, "error", ex.Message));

                _logger.LogError(ex.Message);
            }
        }
Ejemplo n.º 17
0
        public async Task DispatchAsync <T>(T command) where T : ICommand
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command), "Command can not be null");
            }

            await _bus.PublishAsync(command, Guid.NewGuid(),
                                    cfg => cfg
                                    .WithRoutingKey("person.getname")
                                    .WithExchange(ex => ex.WithName("person_exchange").WithType(ExchangeType.Topic).WithAutoDelete())
                                    );
        }
        public async Task HandleAsync(PaymentFailed @event)
        {
            try
            {
                await _historyService.SaveAsync(@event);

                var logCreated = new CreateLog(@event.UserId, @event.PaymentId, LogLevel.Info, "Process_Payment_6",
                                               "Saved Failed Payment");
                await _busClient.PublishAsync(logCreated);

                var historyCreatedEvent = new PaymentHistoryCreated();
                @event.CopyPayment(historyCreatedEvent);
                historyCreatedEvent.Processed = false;
                await _busClient.PublishAsync(historyCreatedEvent);
            }
            catch (Exception ex)
            {
                var logCreated = new CreateLog(@event.UserId, @event.PaymentId, LogLevel.Error, "Save_Payment_Failed",
                                               "Cannot save Failed payment  because :" + ex.Message);
                await _busClient.PublishAsync(logCreated);
            }
        }
Ejemplo n.º 19
0
        public async Task <object> PaymentGatewayCallback(Guid paymentId)
        {
            var paymentInfo = await _genericPaymentRepository.GetByIdAsync(paymentId);

            paymentInfo.PaymentStatus = PaymentStatus.Accepted;
            await _genericPaymentRepository.UpdateAsync(paymentInfo);

            var order = await _restClient.GetAsync <Order>("order_service", $"/api/orders/{paymentInfo.OrderId}");

            await _messageBus.PublishAsync(new PaymentAcceptedEvent(order.SagaId.Value));

            return(null);
        }
        public async Task HandleAsync(CreateActivity command)
        {
            //Console.WriteLine($"Creating activity: {command.Category} {command.Name}");
            _logger.LogInformation($"Creating activity: {command.Category} {command.Name}");
            try
            {
                await _activityService.AddAsync(command.Id,
                                                command.UserId,
                                                command.Category,
                                                command.Name,
                                                command.Description,
                                                command.CreatedAt);

                await _busClient.PublishAsync(new ActivityCreated(command.Id,
                                                                  command.UserId,
                                                                  command.Category,
                                                                  command.Name,
                                                                  command.Description,
                                                                  command.CreatedAt));

                return;
            }
            catch (ActioException ex)
            {
                await _busClient.PublishAsync(new CreateActivityRejected(command.Id,
                                                                         ex.Code,
                                                                         ex.Message));

                _logger.LogError(ex.Message);
            }
            catch (Exception ex)
            {
                await _busClient.PublishAsync(new CreateActivityRejected(command.Id,
                                                                         "Error",
                                                                         ex.Message));

                _logger.LogError(ex.Message);
            }
        }
Ejemplo n.º 21
0
        public async Task PublishSaveEventAsync(Plant plant)
        {
            var e = new PlantSaved {
                Id        = plant.Id,
                Name      = plant.Name,
                GaiaCode  = plant.GaiaCode,
                CountryId = plant.CountryId,
                SOAId     = plant.SOAId,
                IsDeleted = plant.IsDeleted
            };

            await _busClient.PublishAsync <PlantSaved>(e);
        }
Ejemplo n.º 22
0
        public async Task HandleAsync(ChangePassword command)
        {
            _logger.LogInformation($"Processing: {command.Id}");
            try
            {
                await _identityService.ChangePasswordAsync(command.UserId, command.CurrentPassword, command.NewPassword);

                await _busClient.PublishAsync(new OperationCompleted(command.Id, command.UserId, "password-changed", "identity service"));
            }
            catch (ToolBoxException ex)
            {
                await _busClient.PublishAsync(new OperationRejected(command.Id, command.UserId, "password-changed", "identity service", ex.Code, ex.Message));

                _logger.LogError(command.Id.ToString(), ex.Message);
            }
            catch (Exception ex)
            {
                await _busClient.PublishAsync(new OperationRejected(command.Id, command.UserId, "password-changed", "identity service", "error", ex.Message));

                _logger.LogError(command.Id.ToString(), ex.Message);
            }
        }
Ejemplo n.º 23
0
 public async Task HandleAsync(TakeRemarkAction command)
 {
     Participant participant = null;
     await _handler
     .Run(async() =>
     {
         await _remarkActionService.ParticipateAsync(command.RemarkId, command.UserId, command.Description);
         var maybeParticipant = await _remarkActionService.GetParticipantAsync(command.RemarkId, command.UserId);
         participant          = maybeParticipant.Value;
     })
     .OnSuccess(async() => await _bus.PublishAsync(new RemarkActionTaken(command.Request.Id,
                                                                         command.UserId, participant.User.Name, command.RemarkId, command.Description, participant.CreatedAt)))
     .OnCustomError(ex => _bus.PublishAsync(new TakeRemarkActionRejected(command.Request.Id,
                                                                         command.UserId, command.RemarkId, ex.Code, ex.Message)))
     .OnError(async(ex, logger) =>
     {
         logger.Error(ex, $"Error occured while taking action for remark: '{command.RemarkId}' by user: '******'.");
         await _bus.PublishAsync(new TakeRemarkActionRejected(command.Request.Id,
                                                              command.UserId, command.RemarkId, OperationCodes.Error, ex.Message));
     })
     .ExecuteAsync();
 }
Ejemplo n.º 24
0
        public void StartPublishing()
        {
            int n = 1;

            while (n > 0)
            {
                _client.PublishAsync(new HeartbeatMessage {
                    serialNumber = n, timeSent = DateTime.Now
                });
                n++;
                Thread.Sleep(_timeBetweenMsg * 1000);
            }
        }
Ejemplo n.º 25
0
        public async Task HandleAsync(CreateUser command)
        {
            _logger.LogInformation($"Creating user: '******' with name: '{command.Name}'.");
            try
            {
                await _userService.RegisterAsync(command.Email, command.Password, command.Name);

                await _busClient.PublishAsync(new UserCreated(command.Email, command.Name));

                _logger.LogInformation($"User: '******' was created with name: '{command.Name}'.");
            }
            catch (ActioException ex)
            {
                _logger.LogError(ex, ex.Message);
                await _busClient.PublishAsync(new CreateUserRejected(command.Email, ex.Message, ex.Code));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await _busClient.PublishAsync(new CreateUserRejected(command.Email, ex.Message, "error"));
            }
        }
Ejemplo n.º 26
0
        public async Task HandleMessage(MessageWrapper message)
        {
            if (message.MessageBody != null)
            {
                if (message.MessageBody.Length > 0)
                {
                    object testMsg = System.Text.Json.Serialization.JsonSerializer.Parse(
                        message.MessageBody, Type.GetType(message.MessageType));

                    await _client.PublishAsync(testMsg);
                }
            }
        }
Ejemplo n.º 27
0
        public async Task HandleAsync(CreateActivity command)
        {
            Console.WriteLine($"Creating activity:{command.Name}");

            await _busClient.PublishAsync(
                new ActivityCreated(
                    command.Id,
                    command.UserId,
                    command.Category,
                    command.Name,
                    command.Description,
                    command.CreatedAt));
        }
Ejemplo n.º 28
0
 private async Task DbStoredProcedureInvoke(ServerModel server, SqlQueryModel sqlQuery)
 {
     foreach (var database in server.Databases)
     {
         await _busClient.PublishAsync(new SqlStoredProcedureQuery(Guid.NewGuid(),
                                                                   server.UserId,
                                                                   sqlQuery.Query,
                                                                   new Dictionary <string, string> {
             { "@oneresultset", "1" }
         },
                                                                   server.Host,
                                                                   server.Port,
                                                                   server.Login,
                                                                   _protector.Unprotect(server.Password),
                                                                   database.Name,
                                                                   (int)sqlQuery.Name,
                                                                   server.Id,
                                                                   database.Id,
                                                                   "sqlmonitor-service"
                                                                   ));
     }
 }
Ejemplo n.º 29
0
        public async Task <ActionResult> RegisterUser([FromBody] CreateUser createUser)
        {
            var emailTaken = await userService.EmailTakenAsync(createUser.Email);

            if (emailTaken)
            {
                return(BadRequest("Email already taken"));
            }

            await busClient.PublishAsync(createUser);

            return(Accepted($"RegisterUser/{createUser.Email}"));
        }
        public async Task HandleAsync(xItem command)
        {
            try
            {
                var xitem = await _service.GetAsync(command.Item);

                if (xitem == null)
                {
                    await InsertAsync(command);
                }
                else
                {
                    await UpdateAsync(command, xitem);
                }

                return;
            }
            catch (OrderInException ex)
            {
                await _busClient.PublishAsync(new ItemRejected(
                                                  command.Id,
                                                  ex.Code,
                                                  ex.Message
                                                  ));

                _logger.LogError(ex.Message);
            }
            catch (Exception ex)
            {
                await _busClient.PublishAsync(new ItemRejected(
                                                  command.Id,
                                                  "error",
                                                  ex.Message
                                                  ));

                _logger.LogError(ex.Message);
            }
        }