Skip to content

Commit

Permalink
Refactored debug service integrations to now house the debug text
Browse files Browse the repository at this point in the history
  • Loading branch information
Delubear committed Sep 23, 2024
1 parent d703fe3 commit e5993cc
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 42 deletions.
17 changes: 8 additions & 9 deletions GlucoseTray/AppContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ public class AppContext : ApplicationContext
private readonly ILogger<AppContext> _logger;
private readonly IOptionsMonitor<GlucoseTraySettings> _options;
private readonly IGlucoseFetchService _fetchService;
private NotifyIcon _trayIcon;
private GlucoseResult? _currentGlucoseResult = null;
private readonly NotifyIcon _trayIcon;
private readonly UiService _uiService;
private readonly AlertService _alertService;

Expand All @@ -34,18 +33,18 @@ private async void BeginCycle()
{
Application.DoEvents();

_currentGlucoseResult = await _fetchService.GetLatestReadingsAsync();
_uiService.CreateIcon(_currentGlucoseResult);
_alertService.AlertNotification(_currentGlucoseResult);
var currentGlucoseResult = await _fetchService.GetLatestReadingsAsync();
_uiService.CreateIcon(currentGlucoseResult);
_alertService.AlertNotification(currentGlucoseResult);

await Task.Delay(_options.CurrentValue.PollingThresholdTimeSpan);
}
catch (Exception e)
{
MessageBox.Show($"ERROR: {e}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError(e.ToString());
_logger.LogError(e, "An error occurred while fetching the latest glucose readings.");
_trayIcon.Visible = false;
_trayIcon?.Dispose();
_trayIcon.Dispose();
Environment.Exit(0);
}
}
Expand All @@ -55,8 +54,8 @@ private void Exit(object? sender, EventArgs e)
{
_logger.LogInformation("Exiting application.");
_trayIcon.Visible = false;
_trayIcon?.Dispose();
_trayIcon.Dispose();
Application.ExitThread();
Application.Exit();
}
}
}
1 change: 1 addition & 0 deletions GlucoseTray/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ private static void ConfigureServices(IConfiguration configuration, IServiceColl
.AddScoped<IDexcomService, DexcomService>()
.AddScoped<AlertService, AlertService>()
.AddScoped<IExternalCommunicationAdapter, ExternalCommunicationAdapter>()
.AddScoped<DebugService, DebugService>()
.AddScoped<IGlucoseFetchService, GlucoseFetchService>();
}

Expand Down
12 changes: 9 additions & 3 deletions GlucoseTray/Services/DebugService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@

namespace GlucoseTray.Services;

internal static class DebugService
public class DebugService
{
internal static void ShowDebugAlert(Exception ex, string message, string supplementalText = "")
private readonly List<string> DebugText = [];

public void AddDebugText(string text) => DebugText.Add(text);

public void ClearDebugText() => DebugText.Clear();

public void ShowDebugAlert(Exception ex, string message)
{
MessageBox.Show(ex?.Message + ex?.InnerException?.Message + supplementalText, message, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex?.Message + ex?.InnerException?.Message + string.Join(Environment.NewLine, DebugText), message, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
31 changes: 17 additions & 14 deletions GlucoseTray/Services/DexcomService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,25 @@ public interface IDexcomService
public class DexcomService : IDexcomService
{
private readonly IOptionsMonitor<GlucoseTraySettings> _options;
private readonly List<string> DebugText = new();
private readonly ILogger _logger;
private readonly UrlAssembler _urlBuilder;
private readonly IExternalCommunicationAdapter _externalAdapter;
private readonly DebugService _debug;

public DexcomService(IOptionsMonitor<GlucoseTraySettings> options, ILogger<DexcomService> logger, UrlAssembler urlBuilder, IExternalCommunicationAdapter externalAdapter)
public DexcomService(IOptionsMonitor<GlucoseTraySettings> options, ILogger<DexcomService> logger, UrlAssembler urlBuilder, IExternalCommunicationAdapter externalAdapter, DebugService debug)
{
_options = options;
_logger = logger;
_urlBuilder = urlBuilder;
_externalAdapter = externalAdapter;
_debug = debug;
}

public async Task<GlucoseResult> GetLatestReadingAsync()
{
DebugText.Clear();
DebugText.Add("Starting DexCom Fetch");
DebugText.Add("Server: " + _urlBuilder.GetDexComServer());
_debug.ClearDebugText();
_debug.AddDebugText("Starting DexCom Fetch");
_debug.AddDebugText("Server: " + _urlBuilder.GetDexComServer());

GlucoseResult glucoseResult;

Expand All @@ -40,17 +41,17 @@ public async Task<GlucoseResult> GetLatestReadingAsync()
string sessionId = await GetSessionId(accountId);
string response = await GetApiResponse(sessionId);

DebugText.Add("Attempting to deserialize");
_debug.AddDebugText("Attempting to deserialize");
var data = JsonSerializer.Deserialize<List<DexcomResult>>(response)!.First();
DebugText.Add("Deserialized");
_debug.AddDebugText("Deserialized");

glucoseResult = MapToResult(data);
}
catch (Exception ex)
{
_logger.LogError(ex, "Dexcom fetching failed or received incorrect format.");
if (_options.CurrentValue.IsDebugMode)
DebugService.ShowDebugAlert(ex, "Dexcom result fetch", string.Join(Environment.NewLine, DebugText));
_debug.ShowDebugAlert(ex, "Dexcom result fetch");

glucoseResult = GlucoseResult.Default;
}
Expand Down Expand Up @@ -93,11 +94,11 @@ private async Task<string> GetSessionId(string accountId)
var result = await _externalAdapter.PostApiResponseAsync(sessionUrl, sessionIdRequestJson);
var sessionId = result.Replace("\"", "");

if (sessionId.Any(x => x != '0' && x != '-'))
DebugText.Add("Got a valid session id");
if (IsValidId(sessionId))
_debug.AddDebugText("Got a valid session id");
else
{
DebugText.Add("Invalid session id");
_debug.AddDebugText("Invalid session id");
throw new InvalidOperationException("Invalid session id");
}

Expand All @@ -118,14 +119,16 @@ private async Task<string> GetAccountId()
var result = await _externalAdapter.PostApiResponseAsync(accountUrl, accountIdRequestJson);
var accountId = result.Replace("\"", "");

if (accountId.Any(x => x != '0' && x != '-'))
DebugText.Add("Got a valid account id");
if (IsValidId(accountId))
_debug.AddDebugText("Got a valid account id");
else
{
DebugText.Add("Invalid account id");
_debug.AddDebugText("Invalid account id");
throw new InvalidOperationException("Invalid account id");
}

return accountId;
}

private static bool IsValidId(string id) => id.Any(x => x != '0' && x != '-');
}
15 changes: 8 additions & 7 deletions GlucoseTray/Services/ExternalCommunicationAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@ public interface IExternalCommunicationAdapter
public class ExternalCommunicationAdapter : IExternalCommunicationAdapter
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly List<string> DebugText = [];
private readonly DebugService _debug;
private readonly ILogger _logger;
private readonly IOptionsMonitor<GlucoseTraySettings> _options;

public ExternalCommunicationAdapter(IHttpClientFactory httpClientFactory, ILogger<ExternalCommunicationAdapter> logger, IOptionsMonitor<GlucoseTraySettings> options)
public ExternalCommunicationAdapter(IHttpClientFactory httpClientFactory, ILogger<ExternalCommunicationAdapter> logger, IOptionsMonitor<GlucoseTraySettings> options, DebugService debug)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_options = options;
_debug = debug;
}

public async Task<string> PostApiResponseAsync(string url, string? content = null)
Expand Down Expand Up @@ -58,20 +59,20 @@ private async Task<string> DoApiResponseAsync(HttpRequestMessage request)
{
var client = _httpClientFactory.CreateClient();

DebugText.Add("Requesting: " + request.RequestUri);
_debug.AddDebugText("Requesting: " + request.RequestUri);
response = await client.SendAsync(request);
DebugText.Add("Response received with status code: " + response.StatusCode);
_debug.AddDebugText("Response received with status code: " + response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
DebugText.Add("Result: " + result);
_debug.AddDebugText("Result: " + result);

return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Invalid external response.");
DebugText.Add("Error with external communication: " + ex.Message);
_debug.AddDebugText("Error with external communication: " + ex.Message);
if (_options.CurrentValue.IsDebugMode)
DebugService.ShowDebugAlert(ex, "External result fetch", string.Join(Environment.NewLine, DebugText));
_debug.ShowDebugAlert(ex, "External result fetch");
throw;
}
finally
Expand Down
17 changes: 9 additions & 8 deletions GlucoseTray/Services/NightscoutService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,43 @@ public interface INightscoutService
public class NightscoutService : INightscoutService
{
private readonly IOptionsMonitor<GlucoseTraySettings> _options;
private readonly List<string> DebugText = [];
private readonly ILogger _logger;
private readonly UrlAssembler _urlBuilder;
private readonly IExternalCommunicationAdapter _externalAdapter;
private readonly DebugService _debug;

public NightscoutService(IOptionsMonitor<GlucoseTraySettings> options, ILogger<NightscoutService> logger, UrlAssembler urlBuilder, IExternalCommunicationAdapter externalAdapter)
public NightscoutService(IOptionsMonitor<GlucoseTraySettings> options, ILogger<NightscoutService> logger, UrlAssembler urlBuilder, IExternalCommunicationAdapter externalAdapter, DebugService debug)
{
_options = options;
_logger = logger;
_urlBuilder = urlBuilder;
_externalAdapter = externalAdapter;
_debug = debug;
}

public async Task<GlucoseResult> GetLatestReadingAsync()
{
DebugText.Clear();
DebugText.Add("Starting Nightscout Fetch");
DebugText.Add(!string.IsNullOrWhiteSpace(_options.CurrentValue.AccessToken) ? "Using access token." : "No access token.");
_debug.ClearDebugText();
_debug.AddDebugText("Starting Nightscout Fetch");
_debug.AddDebugText(!string.IsNullOrWhiteSpace(_options.CurrentValue.AccessToken) ? "Using access token." : "No access token.");

GlucoseResult result = new();

try
{
var response = await GetApiResponse();

DebugText.Add("Attempting to deserialize");
_debug.AddDebugText("Attempting to deserialize");
var record = JsonSerializer.Deserialize<List<NightScoutResult>>(response)!.Last();
DebugText.Add("Deserialized.");
_debug.AddDebugText("Deserialized.");

result = MapToResult(record);
}
catch (Exception ex)
{
_logger.LogError(ex, "Nightscout fetching failed or received incorrect format.");
if (_options.CurrentValue.IsDebugMode)
DebugService.ShowDebugAlert(ex, "Nightscout result fetch", string.Join(Environment.NewLine, DebugText));
_debug.ShowDebugAlert(ex, "Nightscout result fetch");
}

return result;
Expand Down
2 changes: 1 addition & 1 deletion GlucoseTray/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"appsettings": {
"Version": "15.0.2",
"Version": "15.0.3",
"Url": "https://github.com/Delubear/GlucoseTray"
}
}

0 comments on commit e5993cc

Please sign in to comment.