public async Task <IActionResult> GetAllProducts() { try { _loggerFactory.LogInformation("Fetching all products"); var products = await _repositoryWrapper.Product.FindAll().ConfigureAwait(false); var lstProducts = _mapper.Map <List <ProductsModel> >(products); _loggerFactory.LogInformation($"Returning {lstProducts.Count} products"); return(Ok(lstProducts)); } catch (Exception ex) { _loggerFactory.LogError($"Something went wrong: {ex.Message}", GetSecondaryInfo(ex)); return(StatusCode(500, "Internal server error")); } }
public IActionResult Error(Exception ex) { _logger.LogError(ex, ex.Message); return(View(Constants.Error, new ErrorViewModel() { Message = ex.Message })); }
public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception e) { _logger.LogError(e, "Got an error from an underlying middleware. This will be logged and hidden from client"); await HandleExceptionAsync(httpContext); } }
/// <inheritdoc/> public async Task <Contract> UpdateLastEmailReminderSentAndLastUpdatedAtAsync(int contractId) { var updatedDate = DateTime.UtcNow; var contract = await _repository.GetByIdAsync(contractId); if (contract != null) { contract.LastEmailReminderSent = updatedDate; contract.LastUpdatedAt = updatedDate; await _work.CommitAsync(); _logger.LogInformation($"[UpdateLastEmailReminderSentAndLastUpdatedAtAsync] - Updated successfully the last email reminder sent - Contract Id: {contractId}, Contract Number: {contract.ContractNumber}"); } else { _logger.LogError($"[UpdateLastEmailReminderSentAndLastUpdatedAtAsync] Contract not found - Contract Id {contractId}."); } return(contract); }
public async Task <IActionResult> Edit([FromQuery(Name = "categoryId")] int?id) { try { if (!id.HasValue) { return(NotFound()); } var categoryToEdit = await _categoriesService.GetCategoryByIdAsync <CategoryUpdate>(id.Value); var categoryEditViewModel = _mapper.Map <CategoryUpdate, CategoryEditViewModel>(categoryToEdit); return(View(categoryEditViewModel)); } catch (Exception ex) { _logger.LogError(ex, ex.Message, id); return(RedirectToAction("Index")); } }
public async Task <IList <ActivityLogDto> > GetAllActivityLogs() { _logger.LogInformation("Method GetAllActivityLogs Invoked."); try { return(_mapperAdapter.Map <IList <ActivityLogDto> >(await _allActivityLogsQuery.Get())); } catch (Exception ex) { _logger.LogError(ex, "Method GetAllActivityLogs failed."); throw; } }
/// <summary> /// Accept a fire and forget audit message. /// </summary> /// <param name="message">Audit.</param> public void Accept(ServiceModel.Audit message) { _fireForgetEventHandler.Execute(async a => { try { await a.CreateAsync(message); } catch (Exception ex) { _logger.LogError(ex, $"Unexpected error during fire and forget audit creation of audit message : {message.Message}."); } }); }
private async Task <string> GetDocumentContentAsync(ContractRequest request) { _logger.LogInformation($"[{nameof(GetDocumentContentAsync)}] called with contract number: {request.ContractNumber} and contract version: {request.ContractVersion} and file name: {request.FileName} "); string documentContent = null; try { BlobClient blob = _blobContainerClient.GetBlobClient(request.FileName); if (!blob.Exists()) { throw new BlobException("Blob name does not exist."); } var response = await blob.DownloadAsync(); using var reader = new StreamReader(response.Value.Content); documentContent = reader.ReadToEnd(); } catch (BlobException ex) { _logger.LogError($"[{nameof(GetDocumentContentAsync)}] called with contract number: {request.ContractNumber}, contract version: {request.ContractVersion} and file name: {request.FileName}. Failed with {ex.Message}."); throw new BlobException(request.ContractNumber, request.ContractVersion, request.FileName, ex); } catch (Exception ex) { _logger.LogError($"[{nameof(GetDocumentContentAsync)}] called with contract number: {request.ContractNumber}, contract version: {request.ContractVersion} and file name: {request.FileName}. Failed with {ex.Message}."); throw new BlobException(request.ContractNumber, request.ContractVersion, request.FileName, ex); } if (string.IsNullOrWhiteSpace(documentContent)) { _logger.LogError($"[{nameof(GetDocumentContentAsync)}] called with contract number: {request.ContractNumber}, contract version: {request.ContractVersion} and file name: {request.FileName}. Failed because blob filename has no content."); throw new BlobNoContentException(request.ContractNumber, request.ContractVersion, request.FileName); } return(documentContent); }
protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { try { TimeSpan?timeSpan = _streamingPlatform.GetUptimeAsync().Result; string message = timeSpan.HasValue ? $"The stream has been going for {timeSpan:hh\\:mm\\:ss}" : "Something's wrong. Are we live right now?"; chatClient.SendMessage(message); } catch (Exception e) { _logger.LogError(e, "Failed trying to get UpTime data."); } }
public async Task <ActionResult <CountResult> > GetCounts() { try { var result = await _statisticsService.GetCounts(); return(Ok(result)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); } return(BadRequest("Unable to return Counts")); }
public async Task <ActionResult <SpeakerMeetSearchResults> > GetResults(string terms) { try { var result = await _searchService.Search(terms); return(Ok(result)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); } return(BadRequest("Unable to return results")); }
protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { string userToCheck = eventArgs?.ChatUser?.DisplayName; try { ChatUser chatUser = Repository.Single(ChatUserPolicy.ByDisplayName(userToCheck)); chatClient.SendMessage($"User {userToCheck} has {chatUser?.Tokens ?? 0} tokens!"); } catch (Exception e) { _logger.LogError(e, $"Failed to look up coins for {userToCheck}."); } }
public void DoSomething(int input) { _logger.LogInformation("Doing something..."); try { // do something that might result in an exception var result = 10 / input; } catch (Exception ex) { // swallow but log the exception _logger.LogError(ex, "An error occurred doing something.", input); } }
/// <inheritdoc/> public XmlDocument ValidateXmlWithSchema(string contents) { _logger.LogInformation($"[{nameof(ValidateXmlWithSchema)}] Attempting to validate xml string."); try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(contents); if (_xmlSchema != null) { var settings = new XmlReaderSettings(); settings.Schemas.Add(_xmlSchema); settings.ValidationType = ValidationType.Schema; xmlDocument.Schemas.Add(_xmlSchema); xmlDocument.Validate(XmlValidationEventHandler); _logger.LogInformation($"[{nameof(ValidateXmlWithSchema)}] Xml validation was successful."); } else { // Schema file is not accessible or not found. // The schema file may not be present if the code is being downloaded from github. // The file should always be present in Azure. _logger.LogWarning($"[{nameof(ValidateXmlWithSchema)}] XML validation failed - Embeded schema file not found."); } return(xmlDocument); } catch (Exception ex) { _logger.LogError(ex, "One or more errors occurred during schema validation."); throw; } }
public async Task Execute(IJobExecutionContext context) { _logger.LogInformation("Start WelcomeJob"); try { await _client.Notify( $@"Hi <!channel>. I'm {_options.ApplicationName}, I am your shifts managing assistant!"); } catch (Exception e) { _logger.LogError(e, $"{e.Message}"); } _logger.LogInformation("WelcomeJob Completed"); }
public async Task ExecuteAsync() { _logger.LogInformation("{service} running at: {time}", nameof(EntryPointService), DateTimeOffset.Now); try { await _queueReceiver.GetMessageFromQueue(""); // Do some work } catch (Exception ex) { _logger.LogError(ex, $"{nameof(EntryPointService)}.{nameof(ExecuteAsync)} threw an exception. "); // TODO: Decide if you want to re-throw which will crash the worker service } }
public override async Task <StartSimulationResponse> StartSimulation(SimulationConfiguration request, ServerCallContext context) { try { if (broker.Status == RuntimeStatus.Waiting) { await broker.StartSimulationAsync(request.ToSimulationOptions(), new CancellationTokenSource().Token); } } catch (NullReferenceException e) { logger.LogError(e, "The simulation {Id} could not be started", request.Id); } return(new StartSimulationResponse()); }
public async Task AddOrderDocumentAsync(string documentType, string workOrderReference, int workOrderId, string processComment) { _logger.LogInformation($"Starting process to add repair request document to UH for work order {workOrderReference}"); try { using (var command = _context.Database.GetDbConnection().CreateCommand()) { _context.Database.OpenConnection(); command.CommandText = "usp_StartHackneyProcessV2"; command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter { DbType = DbType.String, ParameterName = "@docTypeCode", Value = documentType }); command.Parameters.Add(new SqlParameter { DbType = DbType.String, ParameterName = "@WorkOrderRef", Value = workOrderReference }); command.Parameters.Add(new SqlParameter { DbType = DbType.Int32, ParameterName = "@WorkOrderId", Value = workOrderId }); command.Parameters.Add(new SqlParameter { DbType = DbType.String, ParameterName = "@ProcessComment", Value = processComment }); await command.ExecuteNonQueryAsync(); } } catch (Exception ex) { _logger.LogError(ex.Message); throw new UhwRepositoryException(); } finally { _context.Database.CloseConnection(); } }
public async Task Execute(IJobExecutionContext context) { _logger.LogInformation("Start CalendarJob"); try { var teamMates = (await _alertOwnerService.GetTeamMates()).ToList(); var oldCalendar = (await _alertOwnerService.GetCalendar(teamMates)).ToList(); var patronDays = await _alertOwnerService.GetPatronDays(); var shiftService = _shiftsService .AddPatronDays(patronDays); IEnumerable <Shift> calendar; if (oldCalendar.Any()) { calendar = shiftService .Build(oldCalendar) .ToList(); } else { calendar = shiftService .Build(teamMates) .ToList(); } await _alertOwnerService.ClearCalendar(); await _alertOwnerService.WriteCalendar(calendar); await _httpClient.Notify("Ciao <!channel> e' uscito il nuovo calendario dei turni:"); await _httpClient.Notify(calendar.Select(shift => $"{_converter.FormatValueAsString(shift.Schedule)} - {shift.TeamMate.Name}")); } catch (Exception e) { _logger.LogError(e, $"{e.Message}"); } _logger.LogInformation("CalendarJob Completed"); }
public Cooldown GetActiveCooldown(ChatUser chatUser, IBotCommand botCommand) { if (chatUser.IsInThisRoleOrHigher(UserRole.Mod) || botCommand.IsActiveGame()) { return(new NoCooldown()); } try { PurgeExpiredUserCommandCooldowns(DateTimeOffset.UtcNow); } catch (Exception e) { _loggerAdapter.LogError(e, "Failed to Purge Expried User Command Cooldowns"); } List <CommandUsage> global = GetUsagesByUserSubjectToCooldown(chatUser.DisplayName, DateTimeOffset.UtcNow); if (global != null && global.Any()) { if (!global.Any(x => x.WasUserWarned)) { global.ForEach(x => x.WasUserWarned = true); } return(new UserCooldown { Message = $"Whoa {chatUser.DisplayName}! Slow down there cowboy!" }); } List <CommandUsage> commandCooldown = GetByCommand(botCommand); if (commandCooldown != null && commandCooldown.Any()) { string timeRemaining = botCommand.GetCooldownTimeRemaining().ToExpandingString(); return(new CommandCooldown { Message = $"\"{botCommand.PrimaryCommandText}\" is currently on cooldown - Remaining time: {timeRemaining}" }); } // TODO: Check for UserCommandCooldown needed. return(new NoCooldown()); }
public async Task <object> GetTagReferencenumber(string hackneyhomesId) { _logger.LogInformation($"Get Tag Refernce number for {hackneyhomesId}"); try { using (var command = _context.Database.GetDbConnection().CreateCommand()) { _context.Database.OpenConnection(); command.CommandText = "GetTagReferenceNumber"; command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter { DbType = DbType.String, ParameterName = "@hackneyhomeId", Value = hackneyhomesId }); var tagReference = ""; using (var reader = command.ExecuteReaderAsync().Result) { if (reader.HasRows && reader.Read()) { if (reader["key1"] != null) { tagReference = reader["key1"].ToString().Trim(); } } } return(tagReference); } } catch (Exception ex) { _logger.LogError(ex.Message); throw new UHWWarehouseRepositoryException(); } finally { _context.Database.CloseConnection(); } }
public async Task <Payment> SendPaymentAsync(Payment payment) { try { var bankResponse = await _acquiringBankClient.SendPaymentAsync(payment); payment.Id = bankResponse.PaymentId; payment.IsSuccessful = bankResponse.IsSuccessful; await _paymentRepository.SaveAsync(payment); return(payment); } catch (Exception e) { _logger.LogError(e); throw; } }
public void SaveConfigState() { if (!ShiftConfigFiles()) { _logger.LogError("Unable to manage configuration files, quitting!"); _environment.Exit(10); } try { var configJson = _jsonHelper.SerializeObject(_dnsEntriesConfig, true); _file.WriteAllText(CoreConfig.ConfigFile, configJson); _logger.LogDebug("Updated configuration file"); } catch (Exception ex) { _logger.LogUnexpectedException(ex); _environment.Exit(11); } }
public async Task <IActionResult> Get([FromQuery] SearchCriteriaDTO criteria) { try { var wantlist = await _repository.GetWantlistAsync(_mappingService.MapSearchCriteria(criteria)); if (wantlist == null) { return(NotFound("No Wantlist data found for specified criteria.")); } DiscogsDTO result = _mappingService.MapWantlist(wantlist); return(Ok(result)); } catch (Exception ex) { _logger.LogError($"Exception occured while getting Wantlist: {ex}"); } return(BadRequest()); }
public async Task <JsonResult> GetInspection(string propertyId) { var responseBuilder = new InspectionResponseBuilder(); try { _logger.LogInformation($"Calling ValidatePropertyId() with {propertyId}"); if (!IdValidator.ValidatePropertyId(propertyId)) { _logger.LogError("propertyId has not passed validation"); var developerMessage = "Invalid parameter - propertyId"; var userMessage = "Please provide a valid property id"; return(responseBuilder.BuildErrorResponse( userMessage, developerMessage, 400)); } var _asbestosActions = new AsbestosActions(_asbestosService, _loggerActions); var response = await _asbestosActions.GetInspection(propertyId); return(responseBuilder.BuildSuccessResponse(response)); } catch (MissingInspectionException ex) { _logger.LogError("No inspections returned for propertyId"); var developerMessage = ex.Message; var userMessage = "Cannot find inspection"; return(responseBuilder.BuildErrorResponse( userMessage, developerMessage, 404)); } catch (Exception ex) { var userMessage = "We had some problems processing your request"; return(responseBuilder.BuildErrorResponseFromException(ex, userMessage)); } }
private CommandUsage AttemptToRunCommand(CommandReceivedEventArgs e, IBotCommand botCommand, IChatClient chatClient1) { try { _logger.LogInformation($"{e.ChatUser.DisplayName} is running the {botCommand.GetType().Name} command."); if (e.ChatUser.CanRunCommand(botCommand)) { return(botCommand.Process(chatClient1, e)); } chatClient1.SendMessage( $"Sorry, {e.ChatUser.DisplayName}! You don't have permission to use the !{e.CommandWord} command."); } catch (Exception exception) { _logger.LogError(exception, "Failed to run a command."); } return(null); }
protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { string userToCheck = eventArgs?.ChatUser?.DisplayName; try { string specifiedUser = eventArgs?.Arguments?.FirstOrDefault()?.NoAt(); if (specifiedUser != null) { userToCheck = specifiedUser; } ChatUser chatUser = Repository.Single(ChatUserPolicy.ByDisplayName(userToCheck)); chatClient.SendMessage($"{userToCheck} has {chatUser?.Tokens ?? 0} tokens!"); } catch (Exception e) { _logger.LogError(e, $"Failed to look up coins for {userToCheck}."); } }
public async Task ExecuteAsync() { _logger.LogInformation("{service} running at: {time}", nameof(EntryPointService), DateTimeOffset.Now); try { // capture the image _capture.CaptueImage(_settings); //check the directory for changes //If the directory has a change //Take the image //Upload to the server // check 1 URL in the message //var statusHistory = await _urlStatusChecker.CheckUrlAsync(message, ""); // record HTTP status / response time // _logger.LogInformation("Record HTTP status ,response time {time}", statusHistory); } catch (Exception ex) { _logger.LogError(ex, $"{nameof(EntryPointService)}.{nameof(ExecuteAsync)} threw an exception."); } }
public async Task<JsonResult> GetAddresses([FromQuery]string Postcode = null, [FromQuery]string USRN = null, [FromQuery]string UPRN = null, [FromQuery]GlobalConstants.PropertyClassPrimary? PropertyClass = null, [FromQuery]string PropertyClassCode = null, [FromQuery]GlobalConstants.AddressStatus AddressStatus = GlobalConstants.AddressStatus.ApprovedPreferred, [FromQuery]GlobalConstants.Format Format = GlobalConstants.Format.Simple, [FromQuery]GlobalConstants.Gazetteer Gazetteer = GlobalConstants.Gazetteer.Local, [FromQuery]int? Limit = GlobalConstants.LIMIT, [FromQuery]int? Offset = GlobalConstants.OFFSET) { try { AddressesQueryParams queryParams = new AddressesQueryParams(); queryParams.Postcode = WebUtility.UrlDecode(Postcode); queryParams.UPRN = WebUtility.UrlDecode(UPRN); queryParams.USRN = WebUtility.UrlDecode(USRN); queryParams.PropertyClassCode = WebUtility.UrlDecode(PropertyClassCode); queryParams.PropertyClass = WebUtility.UrlDecode(PropertyClass.ToString()); queryParams.AddressStatus = WebUtility.UrlDecode(AddressStatus.ToString()); queryParams.Gazetteer = WebUtility.UrlDecode(Gazetteer.ToString()); queryParams.Format = WebUtility.UrlDecode(Format.ToString()); ValidationResult validatorFilterErrors = _validator.ValidateAddressesQueryParams(queryParams); if (!validatorFilterErrors.ErrorOccurred) { Pagination pagination = new Pagination(); pagination.limit = Limit ?? default(int); pagination.offset = Offset ?? default(int); var result = await _addressesActions.GetAddresses( queryParams, pagination); var json = Json(new { result, ErrorCode = "0", ErrorMessage = "" }); json.StatusCode = 200; json.ContentType = "application/json"; return json; } else { var errors = validatorFilterErrors.ErrorMessages; var json = Json(errors); json.StatusCode = 400; json.ContentType = "application/json"; return json; } } catch (Exception ex) { var errors = new List<ApiErrorMessage> { new ApiErrorMessage { developerMessage = ex.Message, userMessage = "We had some problems processing your request" } }; _logger.LogError(ex.Message); var json = Json(errors); json.StatusCode = 500; json.ContentType = "application/json"; return json; } }
private void HandleMissingUpdater(DnsUpdaterEntry entry) { _logger.LogError("No updater found for DnsEntry type '{type}'", entry.Type.ToString("G") ); }