Skip to content

Commit

Permalink
Add logging, improve exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
reagcz committed Nov 17, 2022
1 parent e03fbfd commit 5b8b066
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 26 deletions.
24 changes: 22 additions & 2 deletions IdeapadToolkit/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Serilog;
using System.Windows;
using Serilog.Core;

namespace IdeapadToolkit
{
Expand All @@ -23,9 +25,21 @@ namespace IdeapadToolkit
public partial class App : Application
{
private Container _container;
private ILogger _logger;

public static void ConfigureServices(Container container)
public void ConfigureServices(Container container)
{
// For later use
var logLevel = new LoggingLevelSwitch();
logLevel.MinimumLevel = Serilog.Events.LogEventLevel.Error;
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.ControlledBy(logLevel)
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7, levelSwitch: logLevel);
var logger = _logger = loggerConfig.CreateLogger();

container.RegisterInstance(logger);
container.RegisterInstance(logLevel);

container.RegisterSingleton<INavigationService, NavigationService>();
container.RegisterSingleton<ILenovoPowerSettingsService, LenovoPowerSettingsService>();
container.RegisterSingleton<IUEFISettingsService, UEFISettingsService>();
Expand All @@ -46,6 +60,7 @@ protected override void OnStartup(StartupEventArgs e)
base.OnStartup(e);
Container container = _container = new Container();
ConfigureServices(container);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
bool exists = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Environment.ProcessPath)).Length > 1;
if (exists && !e.Args.Contains("ignoreRunning"))
{
Expand All @@ -67,12 +82,17 @@ protected override void OnStartup(StartupEventArgs e)
{
ShowMainWindow(null, null);
}

var iconview = _container.GetInstance<TrayIconView>();
iconview.MakeVisible();
iconview.TrayIconClicked += ShowMainWindow;
}

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_logger.Fatal((Exception)e.ExceptionObject, "Unhandled exception");
}

public void ShowMainWindow(object? sender, EventArgs? e)
{
if (App.Current.MainWindow == null)
Expand Down
2 changes: 2 additions & 0 deletions IdeapadToolkit/IdeapadToolkit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.0.0" />
<PackageReference Include="Hardcodet.NotifyIcon.Wpf" Version="1.1.0" />
<PackageReference Include="ModernWpfUI" Version="0.9.7-preview.2" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="SimpleInjector" Version="5.4.1" />
</ItemGroup>

Expand Down
17 changes: 13 additions & 4 deletions IdeapadToolkit/Services/UEFISettingsService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using IdeapadToolkitService.Helpers;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -14,8 +15,13 @@ public class UEFISettingsService : IUEFISettingsService
private static readonly string Guid = "{D743491E-F484-4952-A87D-8D5DD189B70C}";
private static readonly string ScopeName = "FBSWIF";
private static readonly int ScopeAttribute = 7;
private readonly ILogger _logger;

private static bool SetPrivilege(bool enable)
public UEFISettingsService(ILogger logger)
{
this._logger = logger;
}
private bool SetPrivilege(bool enable)
{
try
{
Expand All @@ -37,8 +43,9 @@ private static bool SetPrivilege(bool enable)
return false;
}
}
catch (Exception)
catch (Exception ex)
{
_logger.Error(ex, "Exception while getting UEFI privilege");
return false;
}
return true;
Expand Down Expand Up @@ -68,8 +75,9 @@ public bool GetFlipToBootStatus()
dataFromUefi = lastWin32Error * -1;
}
}
catch (Exception)
catch (Exception ex)
{
_logger.Error(ex, "Exception while getting UEFI FlipToBoot status");
}
finally
{
Expand Down Expand Up @@ -100,8 +108,9 @@ public int SetFlipToBootStatus(bool newStatus)
var res = (Win32.SetFirmwareEnvironmentVariableExW(ScopeName, Guid, ref structure, Marshal.SizeOf<LenovoFlipToBootSwInterface>(), ScopeAttribute));
if (res != 0) return 0;
}
catch (Exception)
catch (Exception ex)
{
_logger.Error(ex, "Error while setting UEFI FlipToBoot status");
}
finally { _ = SetPrivilege(false); }
return num1;
Expand Down
98 changes: 79 additions & 19 deletions IdeapadToolkit/ViewModels/LenovoSettingsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using IdeapadToolkit.Models;
using IdeapadToolkit.Services;
using ModernWpf.Controls;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -14,28 +15,37 @@ namespace IdeapadToolkit.ViewModels
[CommunityToolkit.Mvvm.ComponentModel.INotifyPropertyChanged]
public partial class LenovoSettingsViewModel
{
public LenovoSettingsViewModel(ILenovoPowerSettingsService lenovoPowerSettingsService, IUEFISettingsService uEFISettingsService, IAdministratorPermissionService administratorPermissionService)
public LenovoSettingsViewModel(ILenovoPowerSettingsService lenovoPowerSettingsService, IUEFISettingsService uEFISettingsService, IAdministratorPermissionService administratorPermissionService, ILogger logger)
{
_lenovoPowerSettingsService = lenovoPowerSettingsService;
_uEFISettingsService = uEFISettingsService;
_administratorPermissionService = administratorPermissionService;
_logger = logger;
}

public void Refresh()
{
Plan = _lenovoPowerSettingsService.GetPowerPlan();
Mode = _lenovoPowerSettingsService.GetChargingMode();
}
private readonly ILenovoPowerSettingsService _lenovoPowerSettingsService;
private readonly IUEFISettingsService _uEFISettingsService;
private IAdministratorPermissionService _administratorPermissionService;
private readonly ILogger _logger;

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsEfficientChecked), nameof(IsIntelligentCoolingChecked), nameof(IsExtremePerformanceChecked))]
private PowerPlan _plan;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsConservationModeEnabled), nameof(IsNormalModeEnabled), nameof(IsRapidModeEnabled))]
private ChargingMode _mode;
private readonly ILenovoPowerSettingsService _lenovoPowerSettingsService;
private readonly IUEFISettingsService _uEFISettingsService;
private IAdministratorPermissionService _administratorPermissionService;
public void Refresh()
{
try
{
Plan = _lenovoPowerSettingsService.GetPowerPlan();
Mode = _lenovoPowerSettingsService.GetChargingMode();
}
catch (Exception ex)
{
_logger.Error(ex, "Exception while fetching current settings");
}
}

#region PowerPlanProperties
public bool IsEfficientChecked
Expand Down Expand Up @@ -73,7 +83,16 @@ public bool IsFlipToBootEnabled
{
if (IsAdministrator)
{
return _uEFISettingsService.GetFlipToBootStatus();
bool res = false;
try
{
_uEFISettingsService.GetFlipToBootStatus();
}
catch (Exception ex)
{
_logger.Error(ex, "Exception while getting FlipToBoot status");
}
return res;
}
else
{
Expand All @@ -82,21 +101,41 @@ public bool IsFlipToBootEnabled
}
set
{
_uEFISettingsService.SetFlipToBootStatus(value);
try
{
_uEFISettingsService.SetFlipToBootStatus(value);
}
catch (Exception ex)
{
_logger.Error(ex, "Exception while setting FlipToBoot status");
}
}
}



public bool IsAlwaysOnUsbEnabled
{
get
{
return _lenovoPowerSettingsService.IsAlwaysOnUsbEnabled();
try
{
return _lenovoPowerSettingsService.IsAlwaysOnUsbEnabled();
}
catch (Exception ex)
{
_logger.Error(ex, "Error while getting Always on usb setting");
return false;
}
}
set
{
_lenovoPowerSettingsService.SetAlwaysOnUsb(value);
try
{
_lenovoPowerSettingsService.SetAlwaysOnUsb(value);
}
catch (Exception ex)
{
_logger.Error(ex, "Error while setting Always on usb setting");
}
OnPropertyChanged(nameof(IsAlwaysOnUsbEnabled));
}
}
Expand All @@ -105,11 +144,26 @@ public bool IsAlwaysOnUsbBatteryEnabled
{
get
{
return _lenovoPowerSettingsService.IsAlwaysOnUsbBatteryEnabled();
try
{
return _lenovoPowerSettingsService.IsAlwaysOnUsbBatteryEnabled();
}
catch (Exception ex)
{
_logger.Error(ex, "Error while getting Always on usb battery setting");
return false;
}
}
set
{
_lenovoPowerSettingsService.SetAlwaysOnUsbBattery(value);
try
{
_lenovoPowerSettingsService.SetAlwaysOnUsbBattery(value);
}
catch (Exception ex)
{
_logger.Error(ex, "Error while setting Always on usb battery setting");
}
}
}
#endregion
Expand Down Expand Up @@ -160,7 +214,10 @@ private void SetChargingMode(int? mode)
_lenovoPowerSettingsService.SetChargingMode((ChargingMode)mode);
Refresh();
}
catch { }
catch (Exception ex)
{
_logger.Error(ex, "Error while setting charging mode");
}
}

[RelayCommand]
Expand Down Expand Up @@ -189,7 +246,10 @@ private void SetPlan(int? plan)
_lenovoPowerSettingsService.SetPowerPlan((PowerPlan)plan);
Refresh();
}
catch { }
catch (Exception ex)
{
_logger.Error(ex, "Exception while setting power plan");
}
}
}

Expand Down
1 change: 1 addition & 0 deletions IdeapadToolkitTests/IdeapadToolkitTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="Moq" Version="4.18.2" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
Expand Down
5 changes: 4 additions & 1 deletion IdeapadToolkitTests/Services/UEFISettingsServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using Serilog;

namespace IdeapadToolkit.Services.Tests
{
Expand All @@ -15,7 +17,8 @@ public class UEFISettingsServiceTests
[TestInitialize]
public void TestInitialize()
{
_service = new UEFISettingsService();
var loggerMock = new Mock<ILogger>();
_service = new UEFISettingsService(loggerMock.Object);
}

[TestMethod()]
Expand Down

0 comments on commit 5b8b066

Please sign in to comment.