public async Task <T> AddAsync(T entity) { _dbContext.Set <T>().Add(entity); try { await _dbContext.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Cannot add entity of type {entity.GetType()}. Error: [{ex.Message}]"); } return(entity); }
public async Task Invoke(HttpContext context, IAppLogger <ErrorHandlerMiddleware> logger) { try { await _next(context); } catch (Exception ex) { var response = context.Response; response.ContentType = "application/json"; var responseModel = new Response <string>() { Succeeded = false, Message = ex.InnerException == null ? ex.Message : ex.InnerException.Message }; switch (ex) { case System.ComponentModel.DataAnnotations.ValidationException e: logger.LogError(e, e.Message); response.StatusCode = StatusCodes.Status400BadRequest; break; case FluentValidation.ValidationException e: logger.LogError(e, e.Message); response.StatusCode = StatusCodes.Status400BadRequest; foreach (var er in e.Errors) { responseModel.Errors.Append(er.ErrorMessage); } break; case KeyNotFoundException e: logger.LogError(e, e.Message); response.StatusCode = StatusCodes.Status404NotFound; break; default: // unhandled error logger.LogError(ex, ex.Message); response.StatusCode = StatusCodes.Status500InternalServerError; break; } var result = JsonSerializer.Serialize(responseModel); await response.WriteAsync(result); } }
public Task <List <Livro> > GetCargaLivros(Stream stream) { List <Livro> livros = new List <Livro>(); try { using var excelPackage = new ExcelPackage(stream); using var excelWorksheet = excelPackage.Workbook.Worksheets.First(); var livrosDto = excelWorksheet.ToList <LivroDto>(); foreach (var livroDto in livrosDto) { var livro = new Livro(livroDto.Titulo, livroDto.Descricao, livroDto.Valor, livroDto.ISBN_10, livroDto.Edicao, livroDto.DataPublicacao, livroDto.Idioma, livroDto.NumeroPaginas, Guid.Parse(livroDto.EditoraId), Guid.Parse(livroDto.AutorId)); livros.Add(livro); } _logger.LogInformation("CSV de carga dos livros convertido com sucesso. Total de livros carregados: {0}", livros.Count); return(Task.FromResult(livros)); } catch (Exception ex) { _logger.LogError(ex, "Erro na conversão do CSV com carga dos livros para o sistema"); throw; } }
public async Task <IActionResult> Index() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); _logger.LogInformation($"Processing json\n{json}"); try { var paymentHandlerEvent = _paymentHandlerEventService.FromJson(json); _logger.LogInformation($"Processing Stripe Event Type: {paymentHandlerEvent.EventType}"); if (paymentHandlerEvent.EventType.Equals(StripeConstants.INVOICE_PAYMENT_SUCCEEDED_EVENT_TYPE)) { await HandleInvoicePaymentSucceeded(json); } else if (paymentHandlerEvent.EventType.Equals(StripeConstants.CUSTOMER_SUBSCRIPTION_DELETED_EVENT_TYPE)) { await HandleCustomerSubscriptionEnded(json); } else if (paymentHandlerEvent.EventType.Equals(StripeConstants.CUSTOMER_SUBSCRIPTION_UPDATED_EVENT_TYPE)) { await HandleCustomerSubscriptionUpdatedEvent(json); } else { throw new Exception($"Unhandled Stripe event type {paymentHandlerEvent.EventType}"); } return(Ok()); } catch (Exception ex) { _logger.LogError(ex, "Stripe callback error", json); throw; } }
public Response <IEnumerable <CustomersDTO> > GetAll() { var response = new Response <IEnumerable <CustomersDTO> >(); try { var customers = _customerDomain.GetAll(); response.Data = _mapper.Map <IEnumerable <CustomersDTO> >(customers); if (response.Data != null) { response.IsSuccess = true; response.Message = "Consulta exitosa!"; _logger.LogInformation(response.Message); } } catch (Exception e) { response.Message = e.Message; _logger.LogError(e.Message, new object[] { e, e }); } return(response); }
public void OnException(ExceptionContext context) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Result = new JsonResult(new ErrorViewModel(context.Exception.Message)); _appLogger.LogError(context.Exception.Message, new[] { context.Exception }); }
internal static App CreateAppFunctionFactory(IServiceProvider provider) { var app = new App(); app.Console.BreakLineInNextWrite = false; app.Items.Add(typeof(IServiceProvider), provider); app.OnBeforeMemberInvoke += (appResult, memberResult) => { IAppLogger <App> logger = provider.GetService <IAppLogger <App> >(); logger.LogDebug("{UserName} vai executar {MethodName}", Environment.UserName, memberResult.Name); }; app.OnAfterMemberInvoke += (appResult, memberResult) => { IAppLogger <App> logger = provider.GetService <IAppLogger <App> >(); logger.LogDebug("{UserName} executou o comando {MethodName}", Environment.UserName, memberResult.Name); }; app.OnException += (appResult, exception) => { IAppLogger <App> logger = provider.GetService <IAppLogger <App> >(); logger.LogError("{UserName} executou um comando que provocou a excepção {ErrorMessage}", Environment.UserName, exception.Message); }; return(app); }
public async Task <GameState> AddEntity(GameState item) { try { await _retryPolicy.ExecuteAsync(async() => { item = await AddGameState(item); }); } catch (Exception ex) { _appLogger?.LogError(ex); throw; } return(item); }
public static async Task SeedAsync(ApplicationDbContext applicationDbContext, IAppLogger <ApplicationDbContext> appLogger, int?retry = 0) { int retryForAvailability = retry.Value; try { // TODO: Only run this if using a real database // context.Database.Migrate(); if (!applicationDbContext.ClientApi.Any()) { applicationDbContext.ClientApi.AddRange(GetClientApi()); await applicationDbContext.SaveChangesAsync(); } } catch (Exception ex) { if (retryForAvailability < 10) { retryForAvailability++; appLogger.LogError(ex.Message.ToString()); await SeedAsync(applicationDbContext, appLogger, retryForAvailability); } throw; } }
public async Task <IActionResult> CreateService(ServiceRequest request) { try { Service service = _mapper.Map(request); service = await _repository.AddAsync(service); return(CreatedAtAction(nameof(GetById), new { id = service.Id }, _mapper.Map(service))); } catch (Exception e) { _logger.LogError(e.Message, e); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public async Task <GameState> AddEntity(GameState item) { try { await _retryPolicy.ExecuteAsync(async() => { var key = await AddGameState(item); item.PlatformKey = key.Path[0].Id.ToString(); }); } catch (Exception ex) { _appLogger?.LogError(ex); throw; } return(item); }
public async Task <IActionResult> Post(CropUnitRequest request) { try { CropUnit cropUnit = _mapper.Map(request); cropUnit = await _repository.AddAsync(cropUnit); return(CreatedAtAction(nameof(GetById), new { id = cropUnit.Id }, _mapper.Map(cropUnit))); } catch (DataStoreException e) { _logger.LogError(e.Message, e, request); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public async Task <IActionResult> Post(WorkItemRequest request) { try { WorkItem workItem = _mapper.Map(request); workItem = await _repository.AddAsync(workItem); return(CreatedAtAction(nameof(GetById), new { id = workItem.Id }, _mapper.Map(workItem))); } catch (DataStoreException e) { _logger.LogError(e.Message, e, request); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public async Task <IActionResult> Post(ProductCategoryRequest request) { try { ProductCategory productCategory = _mapper.Map(request); productCategory = await _repository.AddAsync(productCategory); return(CreatedAtAction(nameof(GetById), new { id = productCategory.Id }, _mapper.Map(productCategory))); } catch (DataStoreException e) { _logger.LogError(e.Message, e, request); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public async Task <IActionResult> Post(SeasonStatusRequest request) { try { SeasonStatus seasonStatus = _mapper.Map(request); seasonStatus = await _repository.AddAsync(seasonStatus); return(CreatedAtAction(nameof(GetById), new { id = seasonStatus.Id }, _mapper.Map(seasonStatus))); } catch (DataStoreException e) { _logger.LogError(e.Message, e, request); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public async Task <IActionResult> Post(OwnershipTypeRequest request) { try { OwnershipType ownershipType = _mapper.Map(request); ownershipType = await _repository.AddAsync(ownershipType); return(CreatedAtAction(nameof(GetById), new { id = ownershipType.Id }, _mapper.Map(ownershipType))); } catch (DataStoreException e) { _logger.LogError(e.Message, e, request); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public lmsObstericAdmissionSheet GetById(int id) { try { if (id == 0) { return(new lmsObstericAdmissionSheet()); } var resultDetails = _objLabManagementEntities.lmsObstericAdmissionSheets.FirstOrDefault(dt => dt.OASID == id); return(resultDetails); } catch (Exception ex) { _objIAppLogger.LogError(ex); return(null); } }
/// <summary> /// Método que consulta si un correo ya se encuentra registrado en la tabla usuarios /// </summary> /// <param name="modelDto">Se manda los datos para el logueo en la app</param> /// <returns>Retorna una entidad de Usuarios</returns> public async Task <Response <UsuariosDTO> > LoginAsync(UsuariosDTO modelDto) { var response = new Response <UsuariosDTO>(); try { var resp = _mapper.Map <Usuarios>(modelDto); var model = await _Domain.LoginAsync(resp); response.Data = _mapper.Map <UsuariosDTO>(model); if (response.Data != null) { response.IsSuccess = true; response.Message = "Consulta Exitosa!"; } } catch (Exception ex) { response.Data = null; response.IsSuccess = false; response.Message = ex.Message; //Manejo de excepciones en el Log _logger.LogError(ex.Message, ex); } return(response); }
public async Task <IActionResult> CreateAccountAsync([FromBody] UserCreateDto APayLoad) { try { if (!ModelState.IsValid) { FAppLogger.LogError(ErrorCodes.INVALID_PAYLOAD); return(StatusCode(400, new ErrorHandlerDto { ErrorCode = nameof(ErrorCodes.INVALID_PAYLOAD), ErrorDesc = ErrorCodes.INVALID_PAYLOAD })); } if (await FLogicContext.Emails.IsEmailAddressExist(APayLoad.EmailAddress)) { FAppLogger.LogWarn(ErrorCodes.EMAIL_ALREADY_EXISTS); return(StatusCode(400, new ErrorHandlerDto { ErrorCode = nameof(ErrorCodes.EMAIL_ALREADY_EXISTS), ErrorDesc = ErrorCodes.EMAIL_ALREADY_EXISTS })); } var LUserId = await FLogicContext.Accounts.SignUp(APayLoad, 12); if (LUserId == 0) { FAppLogger.LogWarn(ErrorCodes.UNEXPECTED_ERROR); return(StatusCode(400, new ErrorHandlerDto { ErrorCode = nameof(ErrorCodes.UNEXPECTED_ERROR), ErrorDesc = ErrorCodes.UNEXPECTED_ERROR })); } FAppLogger.LogInfo($"New user '{APayLoad.EmailAddress}' has been successfully registered."); return(StatusCode(204)); } catch (Exception LException) { FAppLogger.LogFatality(ControllerException.Handle(LException).ErrorDesc); return(StatusCode(500, ControllerException.Handle(LException))); } }
/// <summary> /// Gets all feedbacks. /// </summary> public async Task <ServiceResponse <IEnumerable> > GetAllFeedbacks() { // Note that in a real life application we should catch at the same level, where // Possible exception can be thrown. So we should implement a class which will // give you Success/Failure indicator and data/message instead of catching // all exceptions here try { var feedbacks = await _feedbackRepository.GetAllFeedbacks(); return(ServiceResponse.Ok(feedbacks)); } catch (Exception ex) { _logger.LogError(ex, "Caught an error when tried to get all feedbacks"); return(ServiceResponse.ServerError <IEnumerable>()); } }
public async Task <ModelDto> AddModelAsync(int accountId, ModelDto model) { Guard.AgainstNull(model, "model"); Guard.AgainstAccountNumberMismatch(accountId, model.AccountId, "accountId", "model.AccountId"); var modelEntity = _mapper.Map <ModelDto, Model>(model); try { await _modelRepository.AddAsync(modelEntity); _logger.LogInformation($"Added model, new Id = {modelEntity.Id}"); return(await GetModelByIdAsync(accountId, modelEntity.Id)); } catch (Exception ex) { _logger.LogError(ex, $"Error adding model: {model}."); return(null); } }
public IActionResult Error() { var exception = HttpContext.Features.Get <IExceptionHandlerPathFeature>(); _logger.LogError($"An excption error occurred on { DateTime.Now }", exception); return(View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier })); }
public async Task UpdateVideosThumbnail(AppendOnlyStringList?messages) { var spec = new ArchiveVideoWithoutThumbnailSpec(); var videos = await _repositoryArchiveVideo.ListAsync(spec); foreach (var video in videos) { try { var response = await _getVideoService.ExecuteAsync(video.VideoId); if (response?.Data == null) { continue; } var existThumbsResponse = await _getAllAnimatedThumbnailService.ExecuteAsync(new GetAnimatedThumbnailRequest(long.Parse(video.VideoId !), null)); if (existThumbsResponse.Data.Total <= 0) { var getAnimatedThumbnailResult = await _createAnimatedThumbnailsService.ExecuteAsync(long.Parse(video.VideoId !)); if (getAnimatedThumbnailResult == null || response?.Data.IsPlayable == false) { continue; } video.AnimatedThumbnailUri = getAnimatedThumbnailResult.AnimatedThumbnailUri; } else { video.AnimatedThumbnailUri = existThumbsResponse.Data.Data.FirstOrDefault()?.AnimatedThumbnailUri; } await _repositoryArchiveVideo.UpdateAsync(video); messages?.Append($"Video {video.VideoId} updated with Thumbnails."); } catch (Exception ex) { _logger.LogError(ex, $"Error on Thumbnails for Video {video.VideoId}: {ex.Message}"); } } }
public int Delete(int id) { var resultFlag = 0; try { var deleteObject = _objLabManagementEntities.lmsOtherCaseSheets.FirstOrDefault(x => x.OCSID == id); var detail = _objLabManagementEntities.lmsOtherCaseSheets.Where(x => x.OCSID == id); _objLabManagementEntities.lmsOtherCaseSheets.RemoveRange(detail); _objLabManagementEntities.lmsOtherCaseSheets.Remove(deleteObject); _objLabManagementEntities.SaveChanges(); } catch (Exception ex) { resultFlag = -1; _objIAppLogger.LogError(ex); } return(resultFlag); }
public async Task <string> CreateURLAsync(string extendedURL) { Guard.Against.NullOrEmpty(extendedURL, "URL value"); Guard.Against.OutOfRange(extendedURL.Length, "URL value", 1, _config.MaxURLChars); string res = null; try { ShortURL surl = ShortURL.ComputeShortURLFromExtendedURL(extendedURL); if (!await _urlRepository.ExistsAsync(surl)) { URL newURL = new URL(extendedURL, surl); await _urlRepository.AddAsync(newURL); } res = RemoveBase64Strings(surl.ToString()); } catch (Exception excp) { _logger.LogError(excp, $"Error creating url with value: {extendedURL}."); } return(res); }
private void Logger(Exception ex, string message) { var errorMessage = (ex.InnerException?.Message != null ? ex.InnerException.Message : ex.Message); var className = this.GetType().Name; MethodBase method = MethodBase.GetCurrentMethod(); string methodName = method.ReflectedType.Name; string fullMethodName = className + " " + methodName; _logger.LogError(message + errorMessage + ", " + fullMethodName); }
public async Task <Response <string> > InsertAsync(CorrespondenceDTO model) { var response = new Response <string>(); try { var resp = _mapper.Map <Correspondence>(model); response.Data = await _CorrespondencesDomain.InsertAsync(resp); if (response.Data == "Success") { response.IsSuccess = true; response.Message = "Se ha registrado la Correspondencia exitosamente."; } else { response.IsSuccess = false; response.Message = "Ha ocurrido un error inesperado, por favor intente nuevamente"; _logger.LogWarning("Ha ocurrido un error inesperado, por favor intente nuevamente " + response.Data); } } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; _logger.LogError(ex.Message); } return(response); }
public async Task <Response <string> > InsertAsync(UserDTO model) { var response = new Response <string>(); try { var resp = _mapper.Map <User>(model); response.Data = await _Domain.InsertAsync(resp); if (response.Data == "Success") { response.IsSuccess = true; response.Message = "Se ha registrado el User exitosamente."; } else { response.IsSuccess = false; response.Message = "Ha ocurrido un error inesperado, por favor intente nuevamente"; _logger.LogWarning("Ha ocurrido un error inesperado registrando el usuario " + model.Username + ", (" + response.Data + ")"); } } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; _logger.LogError(ex.Message); } return(response); }
public async Task <FlightDto> AddFlightAsync(int accountId, FlightDto flight) { Guard.AgainstNull(flight, "flight"); Guard.AgainstAccountNumberMismatch(accountId, flight.AccountId, "accountId", "flight.AccountId"); var flightEntity = _mapper.Map <FlightDto, Flight>(flight); try { flightEntity = await _flightRepository.AddAsync(flightEntity); _logger.LogInformation($"Added flight, new Id = {flightEntity.Id}"); await UpdateFlightCountForModel(accountId, flightEntity.ModelId); return(await GetFlightByIdAsync(accountId, flightEntity.Id)); } catch (Exception ex) { _logger.LogError(ex, $"Error adding flight: {flight}."); throw; } }
private ObjectResult InternalServerError( string methodName, string title, Exception ex) { var statusCode = StatusCodes.Status500InternalServerError; var errorMessage = string.Format($"EXCEPTION: UserLoanController::{methodName}() >> StatusCode: {statusCode}, Message: '{ex.Message}'"); var problemDetail = new ProblemDetails() { Status = statusCode, Instance = HttpContext != null?HttpContext.Request.Path.ToString() : "Test", Title = title, Detail = errorMessage }; _appLogger.LogError(errorMessage); return(new ObjectResult(problemDetail) { ContentTypes = { Constants.Http.ContentType }, StatusCode = StatusCodes.Status500InternalServerError }); }