public Task Execute(string name, DateTime birthdate) { var modelState = new Notification(); if (!(name?.Length > 0)) { modelState.Add(nameof(name), "Name has length smaller than 0"); } else if (!name.Contains(' ')) { modelState.Add(nameof(name), "Name has a bad format"); } var now = DateTime.UtcNow; if (birthdate > now.AddYears(-18)) { modelState.Add(nameof(birthdate), "Minor is not allowed"); } if (birthdate < now.AddYears(-150)) { modelState.Add(nameof(birthdate), "Immortals not allowed"); } if (modelState.IsValid) { return(_useCase.Execute(name, birthdate)); } _outputPort?.Invalid(modelState); return(Task.CompletedTask); }
public static Notification AsNotification(this IdentityResult result) { Notification retNotification = Notification.Success(); if (result == null) { retNotification.Add("Ah Snap! We could not process your identity!"); return(retNotification); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { retNotification.Add(error); } } if (retNotification.IsValid()) { //No ModelState errors are available to send, so just return an empty BadRequest. retNotification.Add("What HO! Identity malfunction discovered. AAARRRGH!"); } } return(retNotification); }
public bool IsValid(Notification notification) { if (string.IsNullOrEmpty(Nome)) { notification.Add("O campo [Nome] não foi recebido"); } if (string.IsNullOrEmpty(Email)) { notification.Add("O campo [Email] não foi recebido"); } if (string.IsNullOrEmpty(Senha)) { notification.Add("O campo [Senha] não foi recebido"); } if (string.IsNullOrEmpty(ConfirmacaoSenha)) { notification.Add("O campo [Confirmacao Senha] não foi recebido"); } if (!string.IsNullOrEmpty(Senha) && !string.IsNullOrEmpty(ConfirmacaoSenha) && !Senha.Equals(ConfirmacaoSenha)) { notification.Add("Os campos [Senha] e [Confirmação Senha] estão divergentes"); } return(!notification.Any); }
public void GetVerificaEmailCadastrado(string email) { if (_usuarioRepository.VerificaEmailCadastrado(email)) { _notification.Add("Email ja está cadastrado!!"); } }
public async Task <Provider> Add(Provider provider) { var dulicateEmail = (await _repository.Get(x => x.Email.Trim().Equals(provider.Email.Trim()))).Any(); if (dulicateEmail) { _notification.Add("Email already used"); return(null); } using var transaction = await _repository.BeginTransaction(); await _repository.Add(provider); await SendWelcomeEmail(provider); if (provider.Documents.Any()) { await UploadDocuments(provider); } await transaction.CommitAsync(); return(provider); }
/// <inheritdoc /> public Task Execute(Guid accountId, decimal amount, string currency) { var modelState = new Notification(); if (accountId == Guid.Empty) { modelState.Add(nameof(accountId), "AccountId is required."); } if (currency != Currency.Dollar.Code && currency != Currency.Euro.Code && currency != Currency.BritishPound.Code && currency != Currency.Canadian.Code && currency != Currency.Real.Code && currency != Currency.Krona.Code) { modelState.Add(nameof(currency), "Currency is required."); } if (amount <= 0) { modelState.Add(nameof(amount), "Amount should be positive."); } if (modelState.IsValid) { return(this._useCase .Execute(accountId, amount, currency)); } this._outputPort? .Invalid(modelState); return(Task.CompletedTask); }
public bool IsValid(Notification notification) { if (string.IsNullOrEmpty(Nome)) { notification.Add("O campo Nome não foi recebido"); } if (string.IsNullOrEmpty(Email)) { notification.Add("O campo Email não foi recebido"); } if (string.IsNullOrEmpty(Senha)) { notification.Add("O campo Senha não foi recebido"); } if (string.IsNullOrEmpty(ConfirmacaoSenha)) { notification.Add("O campo Confirmacao Senha não foi recebido"); } if (!string.IsNullOrEmpty(Senha) && !string.IsNullOrEmpty(ConfirmacaoSenha) && !Senha.Equals(ConfirmacaoSenha)) { notification.Add("Senha não confere com a comfirmação"); } return(!notification.Any); }
public void Post(ContaFinanceiraDto conta) { if (string.IsNullOrEmpty(conta.Nome)) { _notification.Add("O Nome da conta é obrigatório"); return; } conta.Nome = conta.Nome.Trim(); var contasAtuais = _contaFinanceiraRepository.GetAll(conta.IdUsuarioCadastro).ToList(); if (contasAtuais.Any(x => x.IdTipo == conta.IdTipo && x.Nome.Trim().ToLower().Equals(conta.Nome.ToLower()))) { _notification.Add($"Já existe uma conta do Tipo: {contasAtuais.First().NomeTipo}, com o Nome: {conta.Nome}"); return; } if (!string.IsNullOrEmpty(conta.Descricao)) { conta.Descricao = conta.Descricao.Trim(); } _contaFinanceiraRepository.Post(conta); }
public void Should_not_overwrite_any_NotificationMessages_that_already_exist() { var source = new Notification(); source.Add(new NotificationMessage(NotificationSeverity.Warning, "")); var destination = new Notification(); destination.Add(new NotificationMessage(NotificationSeverity.Error, "")); destination.Add(source); Assert.AreEqual(2, destination.Messages.Count()); }
public void Should_not_add_any_message_that_is_identical_to_a_message_already_contained_by_the_Notification() { var source = new Notification(); source.Add(new NotificationMessage(NotificationSeverity.Warning, "")); source.Add(new NotificationMessage(NotificationSeverity.Error, "dup")); var destination = new Notification(); destination.Add(new NotificationMessage(NotificationSeverity.Error, "dup")); destination.Add(source); Assert.AreEqual(2, destination.Messages.Count()); }
private void DisplayInfo_Load(object sender, EventArgs e) { string filePath = $"{_currentDirectory}\\{GlobalConfig.BackupAppFileInfo}"; BackupModel backupModel = filePath.LoadFile().ConvertToBackUpModel(); Backup backup = new Backup(new SharpCompression()); bool status = backup.Create(_currentDirectory, backupModel); //this.notifyIcon.Icon = (status == true) ? // new Icon(_backupIcon[BackupIconType.SUCCESSFUL]) : // new Icon(_backupIcon[BackupIconType.ERROR]); //this.notifyIcon.Text = (status == true) ? // $"Backup OK - {DateTime.Now}" : // $"Backup Error - {DateTime.Now}"; string messageContent = ""; if (status == true) { this.notifyIcon.Icon = new Icon(_backupIcon[BackupIconType.SUCCESSFUL]); this.notifyIcon.Text = $"Backup OK - {DateTime.Now}"; messageContent = $"Backup successful - Date: {DateTime.Now}"; } else { this.notifyIcon.Icon = new Icon(_backupIcon[BackupIconType.ERROR]); this.notifyIcon.Text = $"Backup Error - {DateTime.Now}"; messageContent = $"Backup unsuccessful - Date: {DateTime.Now}"; } string emailConfigFilePath = $"{_currentDirectory}\\{GlobalConfig.EmailConfig}"; string notificationFilePath = $"{_currentDirectory}\\{GlobalConfig.BackupAppNotifFileInfo}"; Notification notification = new Notification(); if (File.Exists(emailConfigFilePath)) { EmailModel emailModel = emailConfigFilePath.LoadFile().ConvertToEmailModel(); emailModel.Body = messageContent; notification.Add(new Email(emailModel)); } if (File.Exists(emailConfigFilePath)) { notification.Add(new Text(messageContent, notificationFilePath)); } notification.Send(); Thread.Sleep(60 * 1000); this.Close(); }
public void ToString_Call_ReturnsErrorSummary() { const string error1 = "test"; const string error2 = "another"; _notification.Add(error1); _notification.Add(error2); string summary = _notification.ToString(); Assert.IsTrue(summary.Contains(error1), "Expected error 1 to be in the error summary"); Assert.IsTrue(summary.Contains(error2), "Expected error 2 to be in the error summary"); }
public void Post(ContaConjuntaDto contaConjunta) { var usuarioConvidado = _usuarioRepository.Get(null, contaConjunta.EmailUsuarioConvidado); if (usuarioConvidado == null) { _notification.Add("Não foi encontrado nenhum usuário com o e-mail informado."); return; } if (usuarioConvidado.Id == contaConjunta.IdUsuarioEnvio) { _notification.Add("O e-mail informado não pode ser o mesmo do usuário desta conta"); return; } if (_contaConjuntaRepository.Get(null, contaConjunta.IdConta).Any(x => x.IdUsuarioConvidado == usuarioConvidado.Id && contaConjunta.IndicadorAprovado == "A")) { _notification.Add("O usuário já esta vinculado com esta conta"); return; } contaConjunta.IdUsuarioConvidado = usuarioConvidado.Id; _contaConjuntaRepository.OpenTransaction(); _contaConjuntaRepository.Post(contaConjunta); var conta = _contaFinanceiraRepository.Get(contaConjunta.IdConta); _notificacaoRepository.Post(new NotificacaoDto { IdTipo = 1, // Convite para conta conjunta IdUsuarioEnvio = contaConjunta.IdUsuarioEnvio, IdUsuarioDestino = contaConjunta.IdUsuarioConvidado, Mensagem = $"Deseja compartilhar sua conta {conta.Nome.ToUpper()} com você", ParametrosUrl = null // Não implementado nessa versão do sistema }); // Cadastra notificações para todos os usuarios (caso seja conta conjunta) var msg = $"Enviou um convite para compartilhar a conta {conta.Nome.ToUpper()} com o usuário {usuarioConvidado.Nome}"; _notificacaoService.Post(contaConjunta.IdUsuarioEnvio, conta.Id, 1, msg, new List <int> { contaConjunta.IdUsuarioConvidado }); // 1: Convite para conta conjunta _contaConjuntaRepository.CommitTransaction(); }
protected new IActionResult BadRequest(ModelStateDictionary modelState) { var errors = modelState.Values.SelectMany(x => x.Errors).ToList(); errors.ForEach(x => _notification.Add(x.ErrorMessage)); return(Content(HttpStatusCode.BadRequest, _notification.Get)); }
public async Task ExecuteAsync(string userId, int postId) { var post = await _postRepository.GetAsync(postId); if (post is null || post.UserId != userId) { _outputPort.NotFound(); return; } var result = await _imageService.RemoveAsync(post.Image); if (result.IsT1) { _notification.Add("Detail", result.AsT1.Value); _outputPort.Error(); return; } await _postRepository.RemoveAsync(postId); _outputPort.Ok(); }
public bool IsValid(Notification notification) { var camposObrigatorios = new List <string>(); if (Cnpj == default(decimal)) { camposObrigatorios.Add("Cnpj"); } if (string.IsNullOrEmpty(RazaoSocial)) { camposObrigatorios.Add("RazaoSocial"); } if (string.IsNullOrEmpty(NomeFantasia)) { camposObrigatorios.Add("NomeFantasia"); } if (camposObrigatorios.Any()) { notification.Add("Favor informar os campos: " + string.Join(", ", camposObrigatorios)); } return(!notification.Any); }
public void Should_succeed_if_the_Notification_being_added_has_no_messages() { var source = new Notification(); var destination = new Notification(); destination.Add(source); Assert.AreEqual(0, destination.Messages.Count()); }
private async Task <Notification> SaveItem <T>(T item, ModelUpdateEvent updateEvent) where T : ModelBase { Notification retNotification = Notification.Success(); try { if (updateEvent == ModelUpdateEvent.Created) { if (string.IsNullOrWhiteSpace(item.Id)) { item.Id = Guid.NewGuid().ToString(); } await _database.InsertAsync(item); } else { await _database.UpdateAsync(item); } } catch (SQLiteException) { //LOG: retNotification.Add(new NotificationItem("Save Failed")); } return(retNotification); }
public async Task <IActionResult> PostUpdate([FromBody] ListViewModel vm) { if (ModelState.IsValid) { var owner = await userManager.GetUserAsync(HttpContext.User); try { await Models.Database.Update.PostUpdate(vm, owner, context, hostingEnvironment); vm.IdeaEx = IdeaEx.IdeaByIdAndOwner(vm.IdeaId, owner, context); foreach (Favorite fav in vm.IdeaEx.Idea.Favorites) { Notification.Add(NotificationType.Update, fav.Owner, owner, vm.IdeaEx.Idea, context); } var JsonData = JsonConvert.SerializeObject(vm, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(JsonData)); } catch (Exception ex) { ex = ex; } } var JsonDataError = JsonConvert.SerializeObject(ModelState.Values, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(JsonDataError)); }
public async Task <IActionResult> PostComment([FromBody] ListViewModel vm) { if (ModelState.IsValid) { try { var owner = await userManager.GetUserAsync(HttpContext.User); var idea = context.Ideas.Include(r => r.Stats).Include(r => r.Comments).Include(r => r.Owner).FirstOrDefault(r => r.Id == vm.IdeaId); if (idea.Owner != owner) { Notification.Add(NotificationType.Commented, idea.Owner, owner, idea, context); } Comment.Add(owner, idea, vm.Comment); UserStats.AddComment(owner, context); Stats.AddComments(idea); await context.SaveChangesAsync(); var ideaEx = IdeaEx.IdeaById(vm.IdeaId, owner, context); var JsonData = JsonConvert.SerializeObject(ideaEx, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(JsonData)); } catch (Exception ex) { ex = ex; } } else { var JsonDataError = JsonConvert.SerializeObject(ModelState.Values, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(JsonDataError)); } return(Json("")); }
public async Task ExecuteAsync(string userId, string title, string content, Stream image, string extension) { var post = new Post { Title = title, Content = content, CreatedAt = DateTime.Now, UserId = userId, Image = $"{Guid.NewGuid()}{extension}" }; var result = await _imageService.UploadAsync(post.Image, image); if (result.IsT1) { _notification.Add("Detail", result.AsT1.Value); _outputPort.Error(); return; } await _postRepository.AddAsync(post); _outputPort.Ok(); }
public void Should_return_true_if_Messages_contains_only_messages_with_Info_Severity() { var notification = new Notification(); var messageTest = new NotificationMessage(NotificationSeverity.Info, ""); notification.Add(messageTest); Assert.IsTrue(notification.IsValid); }
public static void Fail(this Notification notification, string message) { if (notification != null) { notification.Add(new NotificationItem(message)); } }
public UsuarioDto Get(int?id = null, string email = null) { ExecuteProcedure(Procedures.SP_SelUsuario); AddParameter("Id", id); AddParameter("Email", email); using (var reader = ExecuteReader()) { if (reader.Read()) { return new UsuarioDto { Id = reader.ReadAttr <int>("Id"), Nome = reader.ReadAttr <string>("Nome"), Email = reader.ReadAttr <string>("Email"), Senha = reader.ReadAttr <string>("Senha"), DataCadastro = reader.ReadAttr <DateTime>("DataCadastro"), DataSolConfirmCadastro = reader.ReadAttr <DateTime?>("DataSolConfirmCadastro"), DataConfirmCadastro = reader.ReadAttr <DateTime?>("DataConfirmCadastro"), DataUltimaAlteracao = reader.ReadAttr <DateTime?>("DataUltimaAlteracao"), DataDesativacao = reader.ReadAttr <DateTime?>("DataDesativacao") } } ; _notification.Add("Usuário não encontrado :("); return(null); } }
public async Task <bool> Follow([FromBody] ProfileViewModel vm) { try { var caller = await userManager.GetUserAsync(HttpContext.User); var trackUser = await userManager.FindByNameAsync(vm.UserName); if (trackUser != null) { var follow = new Follow { DateTime = DateTime.Now, Owner = caller, Track = trackUser }; context.Followers.Add(follow); UserStats.AddFollower(trackUser, context); UserStats.AddFollowing(caller, context); if (trackUser != caller) { Notification.Add(NotificationType.NewFollower, trackUser, caller, null, context); } await context.SaveChangesAsync(); return(true); } } catch (Exception ex) { ex = ex; } return(false); }
private static Notification <TOutput> GetResponse <TOutput>(Notification <string> result) { if (result.Item == null) { return(new Notification <TOutput>(result)); } try { var ex = JsonUtility.Deserialize <RemoteException>(result.Item); if (!ex.Message.IsNullOrEmpty() && !ex.StackTrace.IsNullOrEmpty()) { var notification = new Notification <TOutput>(Notification.ErrorFor("Remote returned Exception: " + ex.Message)); notification.Add(Notification.InfoFor(ex.StackTrace)); return(notification); } } catch { } TOutput output; try { output = JsonUtility.Deserialize <TOutput>(result.Item); } catch (Exception exception) { var notification = new Notification <TOutput>(Notification.ErrorFor("caught exception deserializing:\n" + result.Item + "\n" + exception.Message)); return(notification); } return(output); }
private static Notification <string> GetResponse(WebRequest req) { WebResponse response; try { response = req.GetResponse(); } catch (Exception exception) { var notification = new Notification <string>(Notification.ErrorFor("Remote threw Exception: " + exception.Message)); notification.Add(Notification.InfoFor(exception.StackTrace)); return(notification); } var responseStream = response.GetResponseStream(); if (responseStream == null) { return(new Notification <string>(Notification.ErrorFor("received null response stream"))); } using (var reader = new StreamReader(responseStream)) { var s = reader.ReadToEnd(); return(new Notification <string> { Item = s }); } }
public async Task <IActionResult> NewPrucess([FromBody] NewIdeaViewModel vm) { if (ModelState.IsValid) { var owner = await userManager.GetUserAsync(HttpContext.User); var idea = await IdeaEx.NewIdea(vm, owner, context, hostingEnvironment); var followers = Follow.Get(owner, context).Result; foreach (Follow track in followers) { Notification.Add(NotificationType.NewPost, track.Owner, owner, idea, context); } await context.SaveChangesAsync(); var titel = Regex.Replace(idea.Titel.ToLower(), @"\s+", "_"); var json = JsonConvert.SerializeObject(new { Id = idea.Id, Name = titel }, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(json)); } var JsonData = JsonConvert.SerializeObject(ModelState.Values, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(Json(JsonData)); }
public Notification AsNotification() { var notification = new Notification(); notification.Add(Message, Severity); return(notification); }
public void Should_return_false_if_Messages_contains_only_messages_with_Warning_Severity() { var notification = new Notification(); var messageTest = new NotificationMessage(NotificationSeverity.Warning, ""); notification.Add(messageTest); Assert.IsFalse(notification.IsValid); }
public async Task Remove(int id) { var document = await _repository.GetById(id); if (document == null) { _notification.Add("Document not found"); return; } await using var transaction = await _repository.BeginTransaction(); await _repository.Remove(document); await _storageService.Remove(id + ".pdf"); await transaction.CommitAsync(); }
private void RedefinirSenha(int idUsuario, string senhaAtual, string novaSenha) { var usuario = _usuarioRepository.Get(idUsuario); if (usuario == null) { _notification.Add($"Não foi encontrado usuario com o id {idUsuario}"); return; } if (!_usuarioRepository.SenhaCorreta(idUsuario, senhaAtual)) { _notification.Add("A senha atual enviada esta incorreta"); return; } _usuarioRepository.PutSenha(idUsuario, novaSenha); }
public void Put(TransferenciaDto transferencia) { var contaOrigem = _contaFinanceiraRepository.Get(transferencia.IdContaOrigem); var contaDestino = _contaFinanceiraRepository.Get(transferencia.IdContaDestino); var msg = $"Editou a transferência ({transferencia.Descricao} no valor de R$ {transferencia.Valor:N}) da conta {contaOrigem.Nome.ToUpper()} para a conta {contaDestino.Nome.ToUpper()}"; if (transferencia.IdUsuarioUltimaAlteracao == null) { _notification.Add("O Id do usuário que esta realizando a alteração não foi recebido, favor entrar em contato com o suporte"); return; } _transferenciaRepository.OpenTransaction(); _notificacaoService.Post((int)transferencia.IdUsuarioUltimaAlteracao, contaOrigem.Id, 8, msg); // 8: Edição de transferência em conta conjunta _notificacaoService.Post((int)transferencia.IdUsuarioUltimaAlteracao, contaDestino.Id, 8, msg); _transferenciaRepository.Put(transferencia); _transferenciaRepository.CommitTransaction(); }
private Notification ReturnValidation(ExceptionContext context) { Notification errorResponse = new Notification(); if (!((ValidationException)context.Exception).Errors.Any()) { var description = new ErrorDescription(context.Exception.Message); errorResponse.Add(description.ToString()); } foreach (var validationsfailures in ((ValidationException)context.Exception).Errors) { var description = new ErrorDescription(validationsfailures.ErrorMessage); errorResponse.Add(description.ToString()); } return(errorResponse); }
public void Post(LancamentoCategoriaDto categoria) { if (string.IsNullOrEmpty(categoria.Nome)) { _notification.Add("O Nome da categoria é obrigatório"); return; } categoria.Nome = categoria.Nome.Trim(); var categoriasAtual = _lancamentoCategoriaRepository.GetAll(categoria.IdUsuarioCadastro).ToList(); if (categoriasAtual.Any(x => x.Nome.Trim().ToLower().Equals(categoria.Nome.ToLower()))) { _notification.Add($"Já existe uma categoria com o Nome: {categoria.Nome}"); return; } _lancamentoCategoriaRepository.Post(categoria); }
public void Should_copy_the_NotificationMessages_from_the_source_if_the_destination_is_not_Notification_Null() { var source = new Notification(); var notification = new NotificationMessage(NotificationSeverity.Error, ""); source.Add(notification); var destination = new Notification(); destination.Add(notification); Assert.AreEqual(1, destination.Messages.Count()); Assert.AreEqual(notification, destination.Messages.First()); }
public void Should_add_the_message_to_Messages_if_the_Notification_is_not_Notification_Null() { var notification = new Notification(); var messageTest = new NotificationMessage(NotificationSeverity.Warning, ""); notification.Add(messageTest); Assert.AreEqual(1, notification.Messages.Count()); Assert.AreEqual(messageTest, notification.Messages.First()); }
public void Should_not_add_the_message_if_the_Notification_already_contains_an_identical_message() { var notification = new Notification(); const NotificationSeverity notificationSeverity = NotificationSeverity.Warning; const string notificationText = "test"; var messageTest = new NotificationMessage(notificationSeverity, notificationText); notification.Add(messageTest); var secondMessage = new NotificationMessage(notificationSeverity, notificationText); notification.Add(secondMessage); Assert.AreEqual(1, notification.Messages.Count()); Assert.AreEqual(messageTest, notification.Messages.First()); }