public void DeveRetornarExcessaoSeEmailForNulo() { EnvioEmail envioEmail = new EnvioEmail(); envioEmail.EnviarEmail(null); }
public async Task <IActionResult> RecuperaSenha([FromForm] Usuario usuario) { try { ViewBag.Layout = "_Layout"; if (!string.IsNullOrWhiteSpace(usuario.Email)) { if (string.IsNullOrWhiteSpace(ConfiguracaoEmail.Senha) || string.IsNullOrWhiteSpace(ConfiguracaoEmail.SmtpHost) || string.IsNullOrWhiteSpace(ConfiguracaoEmail.SmtpPorta) || string.IsNullOrWhiteSpace(ConfiguracaoEmail.Usuario)) { ViewData["MSG_E"] = "Necessário ter um e-mail configurado no sistema para fazer o envio da recuperação da senha."; } else { using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(string.Concat(urlBase, "usuario/recuperacao/", usuario.Email))) { if (response.StatusCode == HttpStatusCode.OK) { usuario = JsonConvert.DeserializeObject <Usuario>(response.Content.ReadAsStringAsync().Result); usuario.Senha = EnvioEmail.EnviarEmail(usuario.Email, usuario.Nome, usuario.Id); usuario.EncodeSenha(); using (var httpClient2 = new HttpClient()) { using (var response2 = await httpClient.PutAsync(string.Concat(urlBase, "usuario/", usuario.Id), new StringContent(JsonConvert.SerializeObject(usuario), Encoding.UTF8, "application/json"))) { if (response2.StatusCode == HttpStatusCode.OK) { ViewData["MSG_S"] = "Cheque seu e-mail para recuperação da senha."; } else if (response.StatusCode == HttpStatusCode.NotAcceptable) { RetornoErroAPI retornoErroAPI = JsonConvert.DeserializeObject <RetornoErroAPI>(response.Content.ReadAsStringAsync().Result); ViewData["MSG_E"] = retornoErroAPI.Detail; } else { ViewData["MSG_E"] = "Erro ao alterar usuário. Tente novamente mais tarde!"; } } } } else if (response.StatusCode == HttpStatusCode.NotFound) { ViewData["MSG_E"] = "Usuário não encontrado."; } else { ViewData["MSG_E"] = "Erro ao enviar e-mail para recuperação da senha. Tente novamente mais tarde!"; } } } } } else { ViewData["MSG_E"] = "Necessário ter um e-mail válido para recuperar a senha."; } } catch { ViewData["MSG_E"] = "Erro ao enviar e-mail para recuperação da senha. Tente novamente mais tarde!"; } return(View()); }
public override void OnException(HttpActionExecutedContext context) { var ex = GetCorrectException(context.Exception); if (ex is KnownException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message) }); } if (ex is DbEntityValidationException) { DbEntityValidationException e = ex as DbEntityValidationException; string str = ""; foreach (var eve in e.EntityValidationErrors) { str += $"Entity do tipo \"{eve.Entry.Entity.GetType().Name}\" no estado \"{eve.Entry.State}\" possuí os seguintes erros de validação:"; foreach (var ve in eve.ValidationErrors) { string tmpString = $"- Propriedade: \"{ve.PropertyName}\", Erro: \"{ve.ErrorMessage}\""; str += tmpString; } } logger.Info(ex, str); email.EnviarEmail($"Erro de entidade do banco de dados: {str}", ex.GetType().ToString(), ex.Source?.ToString(), ex.StackTrace?.ToString(), ex.Data?.ToString(), ex.TargetSite?.ToString()); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent($"Erro de entidade do banco de dados: {str}") }); } if (ex is DbUpdateException) { logger.Info(ex, ex.Message); email.EnviarEmail("Esse registro não pode ser excluído por possuir dados vinculados!", ex.GetType().ToString(), ex.Source?.ToString(), ex.StackTrace?.ToString(), ex.Data?.ToString(), ex.TargetSite?.ToString()); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Esse registro não pode ser excluído por possuir dados vinculados!") }); } if (ex is WebException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("Usuário não autorizado!") }); } if (ex is UnauthorizedAccessException) { email.EnviarEmail($"{ex.Message}", ex.GetType().ToString(), ex.Source?.ToString(), ex.StackTrace?.ToString(), ex.Data?.ToString(), ex.TargetSite?.ToString()); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message) }); } //Log Critical errors logger.Error(ex, ex.Message); //Debug.WriteLine(ex); if (ex.Message != "Uma tarefa foi cancelada.") { email.EnviarEmail($"Erro interno do servidor. \n {ex.Message}", ex.GetType().ToString(), ex.Source?.ToString(), ex.StackTrace?.ToString(), ex.Data?.ToString(), ex.TargetSite?.ToString()); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { //Content = new StringContent($"Erro desconhecido.\r\n {ex.Message}") Content = new StringContent($"Erro interno do servidor.") }); } }