コード例 #1
0
 public async Task NotificarValidacoesDeDominio(ValidationResult validationResult)
 {
     foreach (var error in validationResult.Errors)
     {
         _notificacaoDeDominio.Handle(new Notification(error.ErrorMessage));
     }
 }
コード例 #2
0
        public bool GerarArquivo(Agendamento agendamento, string id)
        {
            var caminhoDestino = ConfigurationManager.AppSettings["log_executados"];

            if (!Directory.Exists(caminhoDestino))
            {
                _notificationHandler.Handle(new Domain.Notificacoes.DomainNotification_("GeraLogTXT", "Diretório não existe"));
                return(false);
            }

            caminhoDestino = caminhoDestino + @"\" + agendamento.TSK + DateTime.Now.ToString("ddMMyyyyHHmmss") + extensao;

            try
            {
                using (StreamWriter sw = new StreamWriter(caminhoDestino, false, Encoding.UTF8))
                {
                    sw.WriteLine(id + "|" + DateTime.Now.ToString("yyyy-MM-dd"));
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                _notificationHandler.Handle(new Domain.Notificacoes.DomainNotification_("GeraLogTXT", ex.Message));
                return(false);
            }

            return(true);
        }
コード例 #3
0
 protected void NotifyValidationError(ValidationResult validationResult)
 {
     foreach (var error in validationResult.Errors)
     {
         _notification.Handle(new Notification("error", error.ErrorMessage));
     }
 }
コード例 #4
0
 public void NotificarValidacoesErro(ValidationResult validationResult)
 {
     foreach (var error in validationResult.Errors)
     {
         _notificationHandler.Handle(new Notification(error.PropertyName, error.ErrorMessage));
     }
 }
コード例 #5
0
 public Task Handle(TNotification notification, CancellationToken cancellationToken)
 {
     return(_retryPolicy?.ExecuteAsync(
                () =>
                _inner.Handle(notification, cancellationToken))
            ?? throw new NullReferenceException(nameof(_retryPolicy)));
 }
コード例 #6
0
        private void ProcessUsingHandler(INotificationTemplate notificationTemplate, NotificationOptions options, INotificationHandler handler)
        {
            var handlerName = handler.GetType().Name;

            this._logger.LogDebug("Processing notification. handler={0}", handlerName);

            handler.Handle(notificationTemplate, options);
        }
コード例 #7
0
        public void Handle(T notification)
        {
            _inner.Handle(notification);

            //Send to clients
            var hub = GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();

            hub.Clients.All.publish(notification);
        }
コード例 #8
0
        private void ReceiverReceived(object obj, ReceivedEventArgs args)
        {
            var response = _responseParser.ParseToResponse(args.Value);

            if (response.Type == ResponseTypes.Notification)
            {
                _notificationHandler.Handle(response);
            }
            else
            {
                _resultHandler.Handle(response);
            }
        }
コード例 #9
0
        public Announcement Handle(CreateAnnouncement action)
        {
            var usersToNotify = _retrieveUsersToNotifyFactory.Create(action.ActionAgainst)
                                .Get(action.ActionAgainst)
                                .ToList();

            usersToNotify.ForEach(x =>
                                  _notificationHandler.Handle(
                                      new EmailAnnouncement(x, action.ActionAgainst.Message, action.ActionAgainst.Subject)));

            action.NumberOfUsersEmailed = usersToNotify.Count();

            return(action.ActionAgainst);
        }
 public Task Handle(TNotification notification, CancellationToken cancellationToken)
 {
     if (runtimeOptions.SkipOutOfBandDecorators)
     {
         // Skipping is only important for current handler and must be disabled before invoking the handler
         // because the handler might invoke additional inner handlers which might be marked as out-of-band.
         runtimeOptions.SkipOutOfBandDecorators = false;
         return(inner.Handle(notification, cancellationToken));
     }
     else
     {
         EnqueueHangfireJob(inner.GetType(), notification);
         return(Task.CompletedTask);
     }
 }
コード例 #11
0
        public bool Commit()
        {
            if (_notificationHandler.HasNotifications())
            {
                return(false);
            }

            if (_unitOfWork.Commit())
            {
                return(true);
            }

            _notificationHandler.Handle(new Notification("Commit", "Ocorreu um erro ao salvar os dados no banco"));

            return(false);
        }
コード例 #12
0
 public void Handle(TNotification command)
 {
     using (var ambientContext = _ambientDbContextFactory.Create())
     {
         try
         {
             _decorated.Handle(command);
             ambientContext.Commit();
         }
         catch
         {
             ambientContext.Rollback();
             throw;
         }
     }
 }
コード例 #13
0
        public async Task <ICommandResult> Handle(CadastrarFuncionarioCommand command, CancellationToken cancellationToken)
        {
            var result = new CommandResult(false, "Não foi possível cadastrar Funcionário.");

            if (!command.IsValid())
            {
                return(result.AddNotifications("Dados Inválidos!"));
            }

            if (service.ExisteEmail(command.Email))
            {
                return(result.AddNotifications("Email já cadastrado"));
            }

            if (service.ExisteCPF(command.Cpf))
            {
                return(result.AddNotifications("CPF já cadastrado"));
            }

            var funcionario = new Funcionario();

            try
            {
                funcionario = FuncionarioAdapter.CadastrarFuncionarioCommandToFuncionario(command);
                service.Adicionar(funcionario);
            }
            catch (Exception ex)
            {
                return(new CommandResult(false, $"Ocorreu um erro ao cadastrar Funcionário. Erro.: {ex.Message}"));
            }

            new Thread(() => cadastrarFuncionarioEventHandler.Handle(
                           FuncionarioAdapter.FuncionarioToCadastrarFuncionarioEvent(funcionario), CancellationToken.None)
                       ).Start();

            if (!await service.SaveChanges())
            {
                return(result);
            }

            return(new CommandResult(true, "Funcionário cadastrado com sucesso!"));
        }
コード例 #14
0
        public async Task Handshake()
        {
            var webSockets = HttpContext.WebSockets;

            if (webSockets.IsWebSocketRequest)
            {
                WebSocket webSocket = await webSockets.AcceptWebSocketAsync();

                foreach (var order in _ordersRepository.GetOrdersWithDependencies().Where(order => order.Status == Status.InProgress))
                {
                    await Task.Delay(TimeSpan.FromSeconds(20));

                    await _notificationHandler.Handle(webSocket, order);
                }
            }
            else
            {
                HttpContext.Response.StatusCode = 400;
            }
        }
コード例 #15
0
        public async Task <ActionResult> Patch(string username, [FromBody] JsonPatchDocument <Applicant> model)
        {
            if (!ModelState.IsValid)
            {
                NotifyModelStateErrors();
                return(ModelStateErrorResponseError());
            }

            var actualUser = await _dummyUserService.Find(username);

            if (actualUser == null)
            {
                await _notifications.Handle(new DomainNotification("Applicant", "Not found"), CancellationToken.None);
            }
            else
            {
                model.ApplyTo(actualUser);
                await _dummyUserService.Update(actualUser);
            }

            return(ResponsePutPatch());
        }
コード例 #16
0
ファイル: Bus.cs プロジェクト: kouchan/hackaton-iti-zup
 public void Notify(Notification notification)
 {
     _notificationHandler.Handle(notification);
 }
コード例 #17
0
 protected void Handle(string key, string value)
 {
     _notifications.Handle(new Notification(key, value));
 }
        public async Task Handle(T notification, CancellationToken cancellationToken)
        {
            await _decorated.Handle(notification, cancellationToken);

            await _dispatcher.DispatchEventsAsync();
        }
コード例 #19
0
 protected void NotifyError(string message)
 {
     _notification.Handle(new DomainNotification(message));
 }
コード例 #20
0
 public Task Handle(TNotification notification, CancellationToken cancellationToken)
 => transactionScopeHandler.RunInTransactionScope(() => notificationHandler.Handle(notification, cancellationToken));
コード例 #21
0
        public async Task <Uri> GetCroppedUri(Guid name, int withSize, int heightSize, Stream originalStream = null)
        {
            var nameInStorage = GetNameInStorage(name, Tipo.cropped, withSize, heightSize);

            if (originalStream == null)
            {
                if (_linkCache.Cache.ContainsKey(nameInStorage))
                {
                    return(_linkCache.Cache[nameInStorage]);
                }

                if (await _azureBlobStorage.ExistsAsync(nameInStorage))
                {
                    var uri = GetTrueUri(nameInStorage);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }

                var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem  original para gerar a cropped

                if (!await _azureBlobStorage.ExistsAsync(originalNameInStorge))
                {
                    await _notifications.Handle(new DomainNotification("Id", "Imagem não localizada"), new System.Threading.CancellationToken());

                    return(GetErroUri());
                }

                originalStream = await _azureBlobStorage.GetStreamAsync(originalNameInStorge);
            }
            originalStream.Seek(0, SeekOrigin.Begin);
            using (Image <Rgba32> image = SixLabors.ImageSharp.Image.Load(originalStream))
            {
                //verifica se da pra fazer o crop
                if (withSize < image.Width && heightSize < image.Height)
                {
                    Image <Rgba32> result = image.Clone(ctx => ctx.Resize(
                                                            new ResizeOptions
                    {
                        Size = new Size(withSize, heightSize),
                        Mode = ResizeMode.Crop
                    }));
                    var resultStream = new MemoryStream();
                    result.SaveAsPng(resultStream);

                    await _azureBlobStorage.UploadAsync(nameInStorage, resultStream);

                    var uri = GetTrueUri(nameInStorage);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }
                else // se não der pra fazer pega dimensões abaixo das solicitadas
                {
                    double fator = 1;
                    fator = withSize - image.Width > heightSize - image.Height ?   (double)image.Width / (double)withSize :  (double)image.Height / (double)heightSize;
                    var novoWidth = (int)Math.Floor(withSize * fator);

                    if (dimensoes.Where(q => q < novoWidth).Any())
                    {
                        novoWidth = dimensoes.Where(q => q < novoWidth).Max();
                    }
                    var novoHeight = (int)Math.Round(((double)novoWidth / (double)withSize) * heightSize); // para manter a proporção solicitada

                    if (novoWidth != image.Width && novoHeight != image.Height)
                    {
                        var novoUri = await GetCroppedUri(name, novoWidth, novoHeight);

                        _linkCache.Cache.Add(nameInStorage, novoUri);
                        return(novoUri);
                    }

                    //retorna o original se estiver menor q o solicitado e nas proporsoes solicitadas
                    var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem  original para gerar a cropped
                    var uri = GetTrueUri(originalNameInStorge);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }
            }
        }
コード例 #22
0
 protected void NotificarErro(string codigo, string mensagem)
 {
     _notifications.Handle(new Notification(codigo, mensagem));
 }
コード例 #23
0
 public Task Handle(TNotification notification, CancellationToken cancellationToken)
 {
     return(_retryPolicy.ExecuteAsync(() => _inner.Handle(notification, cancellationToken)));
 }