Skip to content

Commit

Permalink
Merge pull request #60 from Delubear/Rewrite
Browse files Browse the repository at this point in the history
.Net 6 Update and App Streamlining
  • Loading branch information
Delubear authored Jan 12, 2022
2 parents 1c0e1a1 + 577c17e commit 641a975
Show file tree
Hide file tree
Showing 39 changed files with 283 additions and 552 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/dotnet-core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: 5.0.100
dotnet-version: 6.x
- name: Install dependencies
run: dotnet restore
- name: Build
Expand All @@ -26,7 +26,7 @@ jobs:
uses: notiz-dev/github-action-json-property@release
with:
# path to json file
path: ./GlucoseTraycore/appsettings.json
path: ./GlucoseTray/appsettings.json
# which property to read
prop_path: appsettings.Version
- name: Create Release
Expand All @@ -37,8 +37,8 @@ jobs:
# An optional set of paths representing artifacts to upload to the release. This may be a single path or a comma delimited list of paths (or globs)
#artifact:
# An optional set of paths representing artifacts to upload to the release. This may be a single path or a comma delimited list of paths (or globs)
#artifacts: './GlucoseTrayCore/bin/Release/net5.0-windows/win-x64/publish/'
artifacts: './GlucoseTrayCore/bin/Release/net5.0-windows/win-x64/publish/GlucoseTrayCore.exe'
#artifacts: './GlucoseTray/bin/Release/net5.0-windows/win-x64/publish/'
artifacts: './GlucoseTray/bin/Release/net6.0-windows/win-x64/publish/GlucoseTray.exe'
# The content type of the artifact. Defaults to raw
#artifactContentType: # optional, default is
# An optional body for the release.
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: 5.0.100
dotnet-version: 6.x
- name: Install dependencies
run: dotnet restore
- name: Build
Expand All @@ -28,6 +28,6 @@ jobs:
uses: notiz-dev/github-action-json-property@release
with:
# path to json file
path: ./GlucoseTraycore/appsettings.json
path: ./GlucoseTray/appsettings.json
# which property to read
prop_path: appsettings.Version
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ publish/
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
#*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
Expand Down
14 changes: 7 additions & 7 deletions GlucoseTray.sln
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28803.202
# Visual Studio Version 17
VisualStudioVersion = 17.0.32014.148
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlucoseTrayCore", "GlucoseTrayCore\GlucoseTrayCore.csproj", "{2778CBCC-020C-4F3D-99BC-E8C231FB7F53}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlucoseTray", "GlucoseTray\GlucoseTray.csproj", "{0A0B15BE-CA2F-4B32-A338-C8B2DF04060E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2778CBCC-020C-4F3D-99BC-E8C231FB7F53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2778CBCC-020C-4F3D-99BC-E8C231FB7F53}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2778CBCC-020C-4F3D-99BC-E8C231FB7F53}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2778CBCC-020C-4F3D-99BC-E8C231FB7F53}.Release|Any CPU.Build.0 = Release|Any CPU
{0A0B15BE-CA2F-4B32-A338-C8B2DF04060E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A0B15BE-CA2F-4B32-A338-C8B2DF04060E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A0B15BE-CA2F-4B32-A338-C8B2DF04060E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A0B15BE-CA2F-4B32-A338-C8B2DF04060E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
78 changes: 8 additions & 70 deletions GlucoseTrayCore/AppContext.cs → GlucoseTray/AppContext.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using GlucoseTrayCore.Data;
using GlucoseTrayCore.Enums;
using GlucoseTrayCore.Services;
using GlucoseTray.Enums;
using GlucoseTray.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
Expand All @@ -9,29 +8,27 @@
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using GlucoseTrayCore.Extensions;
using GlucoseTrayCore.Models;
using GlucoseTray.Extensions;
using GlucoseTray.Models;
using System.Collections.Generic;
using GlucoseTrayCore.Views.Settings;
using GlucoseTray.Views.Settings;

namespace GlucoseTrayCore
namespace GlucoseTray
{
public class AppContext : ApplicationContext
{
private readonly ILogger<AppContext> _logger;
private readonly IOptionsMonitor<GlucoseTraySettings> _options;
private readonly IGlucoseTrayDbContext _context;
private readonly IGlucoseFetchService _fetchService;
private readonly NotifyIcon trayIcon;

private GlucoseResult GlucoseResult = null;
private readonly IconService _iconService;
private readonly TaskSchedulerService _taskScheduler;

public AppContext(ILogger<AppContext> logger, IGlucoseTrayDbContext context, IconService iconService, IGlucoseFetchService fetchService, IOptionsMonitor<GlucoseTraySettings> options, TaskSchedulerService taskScheduler)
public AppContext(ILogger<AppContext> logger, IconService iconService, IGlucoseFetchService fetchService, IOptionsMonitor<GlucoseTraySettings> options, TaskSchedulerService taskScheduler)
{
_logger = logger;
_context = context;
_iconService = iconService;
_fetchService = fetchService;
_options = options;
Expand Down Expand Up @@ -76,8 +73,6 @@ private void ToggleTask(bool enable)

private async void BeginCycle()
{
await CheckForMissingReadings();

while (true)
{
try
Expand All @@ -87,11 +82,7 @@ private async void BeginCycle()
var results = await _fetchService.GetLatestReadings(GlucoseResult?.DateTimeUTC).ConfigureAwait(false);

if (results.Any())
{
LogResultToDb(results);

GlucoseResult = results.Last();
}

CreateIcon();
AlertNotification();
Expand All @@ -100,8 +91,7 @@ private async void BeginCycle()
}
catch (Exception e)
{
if (_options.CurrentValue.EnableDebugMode)
MessageBox.Show($"ERROR: {e}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"ERROR: {e}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError(e.ToString());
trayIcon.Visible = false;
trayIcon?.Dispose();
Expand Down Expand Up @@ -169,43 +159,6 @@ private bool IsAlertTriggered(double glucoseValueMG, double glucoseValueMMOL, do
? directionGlucoseShouldBeToNotAlert == UpDown.Down ? glucoseValueMG >= alertThreshold : glucoseValueMG <= alertThreshold
: directionGlucoseShouldBeToNotAlert == UpDown.Down ? glucoseValueMMOL >= alertThreshold : glucoseValueMMOL <= alertThreshold;

private async Task CheckForMissingReadings()
{
if (_options.CurrentValue.FetchMethod != FetchMethod.NightscoutApi)
return;

GlucoseResult = _context.GlucoseResults.OrderByDescending(a => a.DateTimeUTC).FirstOrDefault();

if (GlucoseResult == null && MessageBox.Show("Do you want to import readings from NightScout?\r\n\r\n(Warning this may take some time.)", "GlucoseTrayCore : No Readings found in local database.", MessageBoxButtons.YesNo) == DialogResult.No)
return;

DateTime startDate = GlucoseResult?.DateTimeUTC ?? DateTime.UtcNow.AddYears(-100);

var sw = new Stopwatch();
sw.Start();
var missingResults = await _fetchService.GetLatestReadings(startDate).ConfigureAwait(false);
sw.Stop();
int count = missingResults.Count;
if (count > 0)
{
var sinceMessage = (GlucoseResult != null) ? $" since last database record at {GlucoseResult.DateTimeUTC} UTC" : "";

if (count == 1)
_logger.LogWarning($"Starting Up : Found 1 reading recorded at {missingResults[0].DateTimeUTC} UTC{sinceMessage}.");
else
_logger.LogWarning($"Found {count} readings between {missingResults[0].DateTimeUTC} and {missingResults[count - 1].DateTimeUTC} UTC{sinceMessage}. Retrieving them took {sw.Elapsed.TotalSeconds:#,##0.##} seconds");

sw.Restart();
_context.GlucoseResults.AddRange(missingResults); // None of these records will be in the database, so just add them all now.
_context.SaveChanges();
sw.Stop();
if (sw.Elapsed.TotalSeconds > 5)
_logger.LogWarning($"Saving {missingResults.Count()} records took {sw.Elapsed.TotalSeconds:#,##0.##} seconds");

GlucoseResult = missingResults.Last();
}
}

private void Exit(object sender, EventArgs e)
{
_logger.LogInformation("Exiting application.");
Expand Down Expand Up @@ -237,20 +190,5 @@ private void CreateIcon()
private void ShowBalloon(object sender, EventArgs e) => trayIcon.ShowBalloonTip(2000, "Glucose", GetGlucoseMessage(GlucoseResult), ToolTipIcon.Info);

private string GetGlucoseMessage(GlucoseResult result) => $"{result.GetFormattedStringValue(_options.CurrentValue.GlucoseUnit)} {result.DateTimeUTC.ToLocalTime().ToLongTimeString()} {result.Trend.GetTrendArrow()}{result.StaleMessage(_options.CurrentValue.StaleResultsThreshold)}";

private void LogResultToDb(List<GlucoseResult> results)
{
if (results.Count > 1)
_logger.LogWarning($"Found {results.Count} readings between {results[0].DateTimeUTC} and {results[results.Count - 1].DateTimeUTC} UTC{(System.Diagnostics.Debugger.IsAttached ? " (Debugging Mode)" : "")}");

foreach (var result in results)
{
if (!_context.GlucoseResults.Any(g => g.DateTimeUTC == result.DateTimeUTC && !result.WasError && g.MgValue == result.MgValue))
{
_context.GlucoseResults.Add(result);
_context.SaveChanges();
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum AlertLevel
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.ComponentModel;

namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum DexcomServerLocation
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum FetchMethod
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum GlucoseUnitType
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum TrendResult
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GlucoseTrayCore.Enums
namespace GlucoseTray.Enums
{
public enum UpDown
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
using GlucoseTrayCore.Enums;
using GlucoseTrayCore.Models;
using GlucoseTray.Enums;
using GlucoseTray.Models;

namespace GlucoseTrayCore.Extensions
namespace GlucoseTray.Extensions
{
public static class GlucoseFetchResultExtensions
{
public static string GetFormattedStringValue(this GlucoseResult fetchResult, GlucoseUnitType type) => type == GlucoseUnitType.MG ? fetchResult.MgValue.ToString() : fetchResult.MmolValue.ToString("0.0");

public static bool IsStale(this GlucoseResult fetchResult, int minutes)
{
var ts = System.DateTime.Now.ToUniversalTime() - fetchResult.DateTimeUTC;
return ts.TotalMinutes > minutes;
}
public static bool IsStale(this GlucoseResult fetchResult, int minutes) => (System.DateTime.Now.ToUniversalTime() - fetchResult.DateTimeUTC).TotalMinutes > minutes;

public static string StaleMessage(this GlucoseResult fetchResult, int minutes)
{
var ts = System.DateTime.Now.ToUniversalTime() - fetchResult.DateTimeUTC;
return ts.TotalMinutes > minutes ? $"\r\n{ts.TotalMinutes:#} minutes ago" : "";
return ts.TotalMinutes > minutes ? $"\r\n{ts.TotalMinutes:#} minutes ago" : string.Empty;
}
}
}
43 changes: 43 additions & 0 deletions GlucoseTray/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using GlucoseTray.Enums;

namespace GlucoseTray.Extensions
{
public static class StringExtensions
{
public static string GetTrendArrow(this TrendResult input)
{
return input switch
{
TrendResult.TripleUp => "⤊",
TrendResult.DoubleUp => "⮅",
TrendResult.SingleUp => "↑",
TrendResult.FortyFiveUp => "↗",
TrendResult.Flat => "→",
TrendResult.FortFiveDown => "↘",
TrendResult.SingleDown => "↓",
TrendResult.DoubleDown => "⮇",
TrendResult.TripleDown => "⤋",
TrendResult.Unknown => "Unknown",
_ => string.Empty,
};
}

public static TrendResult GetTrend(this string direction)
{
// Values for Direction copied from https://github.com/nightscout/cgm-remote-monitor/blob/41ac93f7217b1b7023ec6ad6fc35d29dcf2e4f88/lib/plugins/direction.js
return direction switch
{
"TripleUp" => TrendResult.TripleUp,
"DoubleUp" => TrendResult.DoubleUp,
"SingleUp" => TrendResult.SingleUp,
"FortyFiveUp" => TrendResult.FortyFiveUp,
"Flat" => TrendResult.Flat,
"FortyFiveDown" => TrendResult.FortFiveDown,
"SingleDown" => TrendResult.SingleDown,
"DoubleDown" => TrendResult.DoubleDown,
"TripleDown" => TrendResult.TripleDown,
_ => TrendResult.Unknown,
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<RootNamespace>GlucoseTrayCore</RootNamespace>
<TargetFramework>net6.0-windows</TargetFramework>
<RootNamespace>GlucoseTray</RootNamespace>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>true</PublishTrimmed>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ApplicationIcon />
<StartupObject />
Expand All @@ -16,29 +15,27 @@
<SelfContained>true</SelfContained>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<Platforms>AnyCPU</Platforms>
<ApplicationManifest>app.manifest</ApplicationManifest>

<runtime>
<AppContextSwitchOverrides value = "Switch.System.Windows.DoNotScaleForDpiChanges=false"/>
<AppContextSwitchOverrides value="Switch.System.Windows.DoNotScaleForDpiChanges=false" />
</runtime>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.SQLite" Version="5.0.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
<PackageReference Include="System.Drawing.Common" Version="5.0.0" />
<AdditionalFiles Remove="app.manifest" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
<PackageReference Include="System.IO.FileSystem" Version="4.3.0" />
<PackageReference Include="System.Text.Json" Version="5.0.0" />
<PackageReference Include="TaskScheduler" Version="2.9.0" />
<PackageReference Include="System.Text.Json" Version="6.0.1" />
<PackageReference Include="TaskScheduler" Version="2.9.3" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading

0 comments on commit 641a975

Please sign in to comment.