public async Task <Result <LocationDto> > FetchLocationFromCountry(string country) { try { var value = await GetGeolocationResponse(country); if (value == null || value.Count == 0) { return(Error <LocationDto>(ResultKey.Geolocation.NotFound)); } var location = value.Select(g => new LocationDto { Longitude = double.Parse(g.Longitude, CultureInfo.InvariantCulture), Latitude = double.Parse(g.Latitude, CultureInfo.InvariantCulture) }) .First(); return(Success(location)); } catch (Exception exception) { _loggerAdapter.Error(exception, "There was a problem with retrieving data from Nominatim API"); return(Error <LocationDto>(ResultKey.UnexpectedError)); } }
public async Task Consume(ConsumeContext <WorkItemDeleted> context) { try { if (context.Message == null) { throw new ArgumentNullException("Message is null"); } int workItemId = context.Message.WorkItemId; if (workItemId < 1) { throw new ArgumentException($"Work item should be equal to 1 or higher. Current value: {workItemId}"); } var createdEnitty = await _workItemAuditService.WIDeleted(workItemId, context.Message.OldWorkItem); _logger.Information($"Successfully logged work item deletion. WorkItemAuditId: {createdEnitty.Id}"); } catch (Exception exception) { _logger.Error(exception.Message); return; } }
public async Task <IEnumerable <FileDto> > UploadToAzureAsync(IEnumerable <IFormFile> files) { try { var container = ConnectToContainer(); var filesListDto = new List <FileDto>(); Stream fileStream; foreach (var file in files) { using (fileStream = file.OpenReadStream()) { fileStream = file.OpenReadStream(); var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + Path.GetExtension(file.FileName)); await blockBlob.UploadFromStreamAsync(fileStream); filesListDto.Add(new FileDto { Name = file.FileName, Path = blockBlob.Uri.ToString() }); } } return(filesListDto); } catch (Exception ex) { _logger.Error(ex.Message); return(default);
private void ProcessConfig() { // TODO: [TESTS] (CsvMetricOutput.ProcessConfig) Add tests var rootDir = _environment.CurrentDirectory.AppendIfMissing("\\"); _config.OutputDir = _config.OutputDir .Replace("./", rootDir) .Replace(".\\", rootDir) .Replace("/", "\\") .AppendIfMissing("\\"); _logger.Debug("Output directory set to: {path}", _config.OutputDir); if (!_directory.Exists(_config.OutputDir)) { _directory.CreateDirectory(_config.OutputDir); } if (!_directory.Exists(_config.OutputDir)) { _logger.Error("Unable to create output directory ({dir}) - disabling output", _config.OutputDir ); Enabled = false; return; } _csvFileMask = $"{_config.OutputDir}{{yyyy}}\\{{mm}}\\{{dd}}\\"; if (_config.UseHourlyFolders) { _csvFileMask += "{hh}\\"; } _csvFileMask += "{yyyy}-{mm}-{dd} {hh}-{mod-min}0.csv"; }
public static void LogUnexpectedException <T>(this ILoggerAdapter <T> logger, Exception ex) { logger.Error("An unexpected exception of type {exType} was thrown in {method}. {exMessage}. | {exStack}", ex.GetType().Name, GetFullMethodName(2), ex.Message, ex.HumanStackTrace() ); }
public string Decrypt(string encryptedText) { // TODO: [TESTS] (EncryptionService.Decrypt) Add tests // TODO: [METRICS] (EncryptionService.Decrypt) Add metrics if (!_config.Enabled || string.IsNullOrWhiteSpace(encryptedText)) { return(null); } try { var encryptedBytes = _utils.FromBase64String(encryptedText); using var msDecrypt = new MemoryStream(encryptedBytes); var csDecrypt = _utils.CreateCryptoStream(msDecrypt, _utils.CreateDecryptor(_keyBytes, _ivBytes), CryptoStreamMode.Read ); var fromEncrypt = new byte[encryptedBytes.Length]; csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); var bufferString = _utils.GetString(fromEncrypt); return(bufferString.Replace("\0", "")); } catch (Exception ex) { if (!_config.LogDecryptInput) { return(null); } if (_config.LogDecryptInput) { _logger.Error(ex, "Unable to decrypt: {i}. {s}", encryptedText, ex.HumanStackTrace()); } else { _logger.LogUnexpectedException(ex); } return(null); } }
private void HandleMaxCoolDownRuns() { // TODO: [TESTS] (RabbitConnection.HandleMaxCoolDownRuns) Add tests _logger.Error("It seems that we are unable to connect to RabbitMQ, disabling output"); _connectionEnabled = false; _connectionErrorCount = 0; _coolDownRunCount = 0; _disabledUntil = null; }
private Task HandleExceptionAsync(HttpContext context, string message) { _logger.Error(message); var code = HttpStatusCode.InternalServerError; var result = JsonConvert.SerializeObject(new { error = message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); }
public IActionResult Index() { _loggerAdapter.Debug("Logs Debug"); _loggerAdapter.Information("Logs Information"); _loggerAdapter.Warning("Logs Warning"); _loggerAdapter.Error("Logs Error"); _loggerAdapter.Fatal("Logs Fatal"); _loggerAdapter.WriteMethodInfo("WriteMethodInfo"); return(View()); }
public async Task UpdateApiKeys(string content) { try { await _blobProvider.SetBlobValue(_config.AuthorizedApiKeysBlobObjectName, content); } catch (ArgumentException e) { _loggerAdapter.Error("Unable to update authorized API keys: " + e.Message); throw new ResultException(ResultKey.UnexpectedError); } }
public async Task <Result <IDictionary <string, string> > > GetStringsResources(string languageCode) { try { var stringBlob = await GetStringsBlob(); var dictionary = stringBlob.Strings .Select(entry => new { entry.Key, Value = entry.GetTranslation(languageCode) }).ToDictionary(x => x.Key, x => x.Value); return(Success <IDictionary <string, string> >(dictionary)); } catch (Exception exception) { _loggerAdapter.Error(exception, "There was a problem during fetching the strings resources"); return(Error <IDictionary <string, string> >(ResultKey.UnexpectedError)); } }
private async Task SendNotificationEmails(string languageCode, List <string> notificationEmails, string project, string healthRisk, string lastReportVillage) { try { var(subject, body) = await _emailTextGeneratorService.GenerateEscalatedAlertEmail(languageCode); body = body .Replace("{{project}}", project) .Replace("{{healthRisk}}", healthRisk) .Replace("{{lastReportVillage}}", lastReportVillage); foreach (var email in notificationEmails) { await _emailPublisherService.SendEmail((email, email), subject, body); } } catch (Exception e) { _loggerAdapter.Error(e, $"Failed to send escalation notification emails for project {project} with health risk {healthRisk}"); throw new ResultException(ResultKey.Alert.EscalateAlert.EmailNotificationFailed); } }
public async Task Consume(ConsumeContext <WorkItemUpdated> context) { try { if (context.Message == null) { throw new ArgumentNullException("Message is null"); } int workItemId = context.Message.WorkItemId; var workItem = await _workItemService.GetById(workItemId); if (workItem == null) { throw new ArgumentException("Work item not found"); } var userData = await _userService.GetById(workItem.AssigneeId); if (userData == null) { throw new ArgumentNullException("Assignee not found"); } if (context.Message.NewWorkItem.AssigneeId != context.Message.OldWorkItem.AssigneeId) { await _bus.Publish(new EmailSend { To = userData.Email, Subject = "New work item assignee", Body = $"You are the new assignee for the work item # {workItemId}" }); _logger.Information($"Bus published EmailSend contract with email: {userData.Email}. WorkItemId: {workItemId}"); } if (context.Message.OldWorkItem != context.Message.NewWorkItem) { var createdEntity = await _workItemAuditService.WIUpdated(context.Message.WorkItemId, context.Message.OldWorkItem, newWorkItem : context.Message.NewWorkItem); _logger.Information($"Successfully logged work item editing. WorkItemAuditId: {createdEntity.Id}"); } } catch (Exception exception) { _logger.Error(exception.Message); return; } }
public async Task <bool> ReceiveReport(Report report) { if (report == null) { _loggerAdapter.Error("Received a report with null value."); return(false); } _loggerAdapter.Debug($"Received report: {report}"); switch (report.ReportSource) { case ReportSource.SmsEagle: await _smsEagleHandler.Handle(report.Content); break; default: _loggerAdapter.Error($"Could not find a proper handler to handle a report '{report}'."); break; } return(true); }
// Helper methods private async Task <string> GetBody(ModelBindingContext bindingContext) { // TODO: [TESTS] (TestingBinder.GetBody) Add tests try { using var reader = new StreamReader( bindingContext.ActionContext.HttpContext.Request.Body, Encoding.UTF8 ); var rawBody = await reader.ReadToEndAsync(); return(string.IsNullOrWhiteSpace(rawBody) ? "{}" : rawBody); } catch (Exception ex) { _logger.Error(ex, "Unable to read body: {msg}", ex.Message); return("{}"); } }
public async Task <int> ExecuteAsync( IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null) { // TODO: [TESTS] (MSSqlHelper.ExecuteAsync) Add tests // TODO: [REVISE] (MSSqlHelper.ExecuteAsync) Revise this logic try { return(await cnn.ExecuteAsync(sql, param, transaction, commandTimeout, commandType)); } catch (Exception ex) { // Generate the base alert message var sb = new StringBuilder(); sb.Append($"Error running SQL command on '{cnn.Database}'."); sb.Append(Environment.NewLine + Environment.NewLine); sb.Append($"SQL: {sql}"); // If there was an error passed into the command - serialize and log it if (param != null) { sb.Append(Environment.NewLine + Environment.NewLine); // TODO: [ABSTRACT] (MySqlHelper) Abstract this var jsonArgs = _jsonHelper.SerializeObject(param, true); sb.Append($"Args: {jsonArgs}"); } // Finally append the exception and log it sb.Append(Environment.NewLine + Environment.NewLine); sb.Append($"Exception: {ex.GetType().Name}: {ex.Message}"); _logger.Error(sb.ToString(), ex); throw; } }
private string GetResponseBody(DevHttpResponse response) { // TODO: [TESTS] (DevGrafanaHttpClient.GetResponseBody) Add tests if (response.ResponseType == DevHttpClientResponseType.File) { if (string.IsNullOrWhiteSpace(response.GeneratedResponseBody)) { if (!_file.Exists(response.FilePath)) { // TODO: [EX] (DevGrafanaHttpClient.GetResponseBody) Throw better exception here _logger.Error("Unable to find response file: {path}", response.FilePath); throw new Exception($"Unable to find response file: {response.FilePath}"); } response.GeneratedResponseBody = _file.ReadAllText(response.FilePath); _logger.Trace("Set GeneratedResponseBody using {path}", response.FilePath); } return(response.GeneratedResponseBody); } // TODO: [COMPLETE] (DevGrafanaHttpClient.GetResponseBody) Complete me return(string.Empty); }
public async Task Consume(ConsumeContext <EmailSend> context) { try { if (context.Message == null) { throw new ArgumentNullException("Message is null"); } if (context.Message.To == null) { throw new ArgumentNullException("No email address provided"); } if (context.Message.Subject == null) { throw new ArgumentNullException("Message subject is not provided"); } if (context.Message.Body == null) { throw new ArgumentNullException("Body subject is not provided"); } var message = context.Message; await _mailer.SendMessageAsync(message.To, message.Body, message.Subject); _logger.Information($"Email sent to: {context.Message.To}"); } catch (Exception exception) { _logger.Error(exception.Message); return; } }
private string ResolveMeasurement(LineProtocolPoint point) { // TODO: [TESTS] (MetricService.ResolveMeasurement) Add tests var resolved = _config.MeasurementTemplate; var key = point.Measurement.Split(':')[1]; if (string.IsNullOrWhiteSpace(key)) { return(resolved); } // Have we cached the key before? if (_config.Measurements.ContainsKey(key)) { return(_config.Measurements[key]); } // Generate a NEW measurement for the requested key and log resolved = resolved.Replace("{type}", WorkMetricBuilderType(point)); _logger.Error("Unable to resolve template '{name}' (using: {fallback})", key, resolved); _config.Measurements[key] = resolved; return(resolved); }
public void Error(string message) { Logger.Error(message); }