├── .gitattributes ├── Assets ├── Cancel.png ├── Idle.png ├── Rest.png ├── Work.png ├── info.png ├── money.png ├── Automat.png ├── Minimize.png ├── Settings.png ├── notebook.png ├── DataSheet.png ├── Sounds │ ├── Error.mp3 │ ├── Finish.mp3 │ └── Termination.mp3 ├── WorkLifeBalanceLogo.ico └── WorkLifeBalanceThumb.png ├── appsettings.json ├── Interfaces ├── INavigationService.cs ├── IUpdateCheckerService.cs ├── IMainWindowDetailsService.cs ├── ISecondWindowService.cs ├── IFeaturesServices.cs └── ISoundService.cs ├── ViewModels ├── Base │ ├── MainWindowDetailsPageBase.cs │ ├── ViewModelBase.cs │ ├── SecondWindowPageBase.cs │ └── PageViewModelBase.cs ├── LoadingPageVM.cs ├── SecondWindowVM.cs ├── CloseWarningPageVM.cs ├── OptionsPageVM.cs ├── UpdatePageVM.cs ├── ForceStateMainMenuDetailsPageVM.cs ├── ViewDayDetailsPageVM.cs ├── ForceWorkMainMenuDetailsPageVM.cs ├── BackgroundProcessesViewPageVM.cs ├── SettingsPageVM.cs ├── MainMenuVM.cs ├── ForceWorkPageVM.cs ├── ViewDaysPageVM.cs └── ViewDataPageVM.cs ├── Models ├── VersionData.cs ├── ProcessActivityData.cs ├── AutoStateChangeData.cs ├── AppSettingsData.cs └── DayData.cs ├── Views ├── SettingsPage.xaml.cs ├── ViewDataPage.xaml.cs ├── OptionsPage.xaml.cs ├── CloseWarningPage.xaml.cs ├── BackgroundProcessesViewPage.xaml.cs ├── ViewDayDetailsPage.xaml.cs ├── ViewDaysPage.xaml.cs ├── UpdatePage.xaml.cs ├── LoadingPage.xaml.cs ├── ForceWorkMainMenuDetailsPage.xaml.cs ├── ForceStateMainMenuDetailsPage.xaml.cs ├── ForceWorkPage.xaml.cs ├── LoadingPage.xaml ├── CloseWarningPage.xaml ├── UpdatePage.xaml ├── ForceStateMainMenuDetailsPage.xaml ├── ForceWorkMainMenuDetailsPage.xaml ├── OptionsPage.xaml ├── ViewDayDetailsPage.xaml ├── SettingsPage.xaml └── BackgroundProcessesViewPage.xaml ├── AssemblyInfo.cs ├── Services ├── NavigationService.cs ├── AppStateHandler.cs ├── SoundService.cs ├── FeaturesService.cs ├── Feature │ ├── TimeTrackerFeature.cs │ ├── ActivityTrackerFeature.cs │ ├── FeatureBase.cs │ ├── ForceStateFeature.cs │ ├── StateCheckerFeature.cs │ ├── DataStorageFeature.cs │ └── IdleCheckerFeature.cs ├── MainWindowDetailsService.cs ├── SecondWindowService.cs ├── UpdateCheckerService.cs ├── AppTimer.cs ├── SqlDataAccess.cs ├── LowLevelHandler.cs └── DataBaseHandler.cs ├── Converters ├── NullToVisibilityConverter.cs ├── IntToStringConverter.cs ├── BoolToVisibleConverter.cs ├── BoolToCollapsedConverter.cs ├── DateOnlyToStringConverter.cs └── TimeOnlyToStringConverter.cs ├── SecondWindow.xaml.cs ├── LICENSE ├── WorkLifeBalance.sln ├── Style ├── PageVMBindings.xaml └── Colors.xaml ├── MainWindow.xaml.cs ├── App.xaml ├── README.md ├── app.manifest ├── SecondWindow.xaml ├── WorkLifeBalance.csproj ├── App.xaml.cs └── .gitignore /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Assets/Cancel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Cancel.png -------------------------------------------------------------------------------- /Assets/Idle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Idle.png -------------------------------------------------------------------------------- /Assets/Rest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Rest.png -------------------------------------------------------------------------------- /Assets/Work.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Work.png -------------------------------------------------------------------------------- /Assets/info.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/info.png -------------------------------------------------------------------------------- /Assets/money.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/money.png -------------------------------------------------------------------------------- /Assets/Automat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Automat.png -------------------------------------------------------------------------------- /Assets/Minimize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Minimize.png -------------------------------------------------------------------------------- /Assets/Settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Settings.png -------------------------------------------------------------------------------- /Assets/notebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/notebook.png -------------------------------------------------------------------------------- /Assets/DataSheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/DataSheet.png -------------------------------------------------------------------------------- /Assets/Sounds/Error.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Sounds/Error.mp3 -------------------------------------------------------------------------------- /Assets/Sounds/Finish.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Sounds/Finish.mp3 -------------------------------------------------------------------------------- /Assets/Sounds/Termination.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/Sounds/Termination.mp3 -------------------------------------------------------------------------------- /Assets/WorkLifeBalanceLogo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/WorkLifeBalanceLogo.ico -------------------------------------------------------------------------------- /Assets/WorkLifeBalanceThumb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/szr2001/WorkLifeBalance/HEAD/Assets/WorkLifeBalanceThumb.png -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Debug": true, 3 | "OverrideDbDirectory": "C:\\Users\\szr20\\Desktop", 4 | "UpdateDataAdress": "https://gist.githubusercontent.com/szr2001/606a8a67a77e0eba5a9d0b9b40a902b2/raw" 5 | } -------------------------------------------------------------------------------- /Interfaces/INavigationService.cs: -------------------------------------------------------------------------------- 1 | using WorkLifeBalance.ViewModels.Base; 2 | 3 | namespace WorkLifeBalance.Interfaces 4 | { 5 | public interface INavigationService 6 | { 7 | ViewModelBase NavigateTo() where T : ViewModelBase; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ViewModels/Base/MainWindowDetailsPageBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.ViewModels.Base 8 | { 9 | public class MainWindowDetailsPageBase : PageViewModelBase 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Interfaces/IUpdateCheckerService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.Interfaces 8 | { 9 | public interface IUpdateCheckerService 10 | { 11 | public Task CheckForUpdate(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ViewModels/Base/ViewModelBase.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace WorkLifeBalance.ViewModels.Base 9 | { 10 | public abstract class ViewModelBase : ObservableObject 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Interfaces/IMainWindowDetailsService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using WorkLifeBalance.ViewModels.Base; 4 | 5 | namespace WorkLifeBalance.Interfaces 6 | { 7 | public interface IMainWindowDetailsService 8 | { 9 | public void CloseWindow(); 10 | Task OpenDetailsPageWith(object? args = null) where T : MainWindowDetailsPageBase; 11 | } 12 | } -------------------------------------------------------------------------------- /ViewModels/LoadingPageVM.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.ViewModels 8 | { 9 | public class LoadingPageVM : SecondWindowPageVMBase 10 | { 11 | public LoadingPageVM() 12 | { 13 | PageName = "Loading..."; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Models/VersionData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.Models 8 | { 9 | public class VersionData 10 | { 11 | public string? Version { get; set; } 12 | public string? DownloadLink { get; set; } 13 | public string? UpdateLog { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Views/SettingsPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Controls; 2 | using WorkLifeBalance.ViewModels; 3 | 4 | namespace WorkLifeBalance.Views 5 | { 6 | /// 7 | /// Interaction logic for SettingsPage.xaml 8 | /// 9 | public partial class SettingsPage : Page 10 | { 11 | public SettingsPage() 12 | { 13 | InitializeComponent(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Views/ViewDataPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Controls; 2 | using WorkLifeBalance.ViewModels; 3 | 4 | namespace WorkLifeBalance.Views 5 | { 6 | /// 7 | /// Interaction logic for ViewDataPage.xaml 8 | /// 9 | public partial class ViewDataPage : Page 10 | { 11 | public ViewDataPage() 12 | { 13 | InitializeComponent(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Interfaces/ISecondWindowService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using WorkLifeBalance.ViewModels; 4 | 5 | namespace WorkLifeBalance.Interfaces 6 | { 7 | public interface ISecondWindowService 8 | { 9 | public Action? OnPageLoaded { get; set; } 10 | public void CloseWindow(); 11 | Task OpenWindowWith(object? args = null) where T : SecondWindowPageVMBase; 12 | } 13 | } -------------------------------------------------------------------------------- /Interfaces/IFeaturesServices.cs: -------------------------------------------------------------------------------- 1 | using WorkLifeBalance.Services.Feature; 2 | 3 | namespace WorkLifeBalance.Interfaces 4 | { 5 | public interface IFeaturesServices 6 | { 7 | public bool IsFeaturePresent() where TFeature : FeatureBase; 8 | public void AddFeature() where TFeature : FeatureBase; 9 | public void RemoveFeature() where TFeature : FeatureBase; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Views/OptionsPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.Input; 2 | using System.Windows.Controls; 3 | using WorkLifeBalance.ViewModels; 4 | 5 | namespace WorkLifeBalance.Views 6 | { 7 | /// 8 | /// Interaction logic for OptionsPage.xaml 9 | /// 10 | public partial class OptionsPage : Page 11 | { 12 | public OptionsPage() 13 | { 14 | InitializeComponent(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Views/CloseWarningPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.Input; 2 | using System.Windows.Controls; 3 | using WorkLifeBalance.ViewModels; 4 | 5 | namespace WorkLifeBalance.Views 6 | { 7 | /// 8 | /// Interaction logic for OptionsPage.xaml 9 | /// 10 | public partial class CloseWarningPage : Page 11 | { 12 | public CloseWarningPage() 13 | { 14 | InitializeComponent(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Interfaces/ISoundService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.Interfaces 8 | { 9 | public interface ISoundService 10 | { 11 | public void PlaySound(SoundType type); 12 | 13 | public enum SoundType 14 | { 15 | Warning, 16 | Termination, 17 | Finish 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Views/BackgroundProcessesViewPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Controls; 2 | using WorkLifeBalance.ViewModels; 3 | 4 | namespace WorkLifeBalance.Views 5 | { 6 | /// 7 | /// Interaction logic for BackgroundWindowsViewPage.xaml 8 | /// 9 | public partial class BackgroundProcessesViewPage : Page 10 | { 11 | public BackgroundProcessesViewPage() 12 | { 13 | InitializeComponent(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Views/ViewDayDetailsPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using System.Windows; 3 | using System.Windows.Controls; 4 | using WorkLifeBalance.Models; 5 | using WorkLifeBalance.ViewModels; 6 | 7 | namespace WorkLifeBalance.Views 8 | { 9 | /// 10 | /// Interaction logic for ViewDayDetailsPage.xaml 11 | /// 12 | public partial class ViewDayDetailsPage : Page 13 | { 14 | public ViewDayDetailsPage() 15 | { 16 | InitializeComponent(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ViewModels/Base/SecondWindowPageBase.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System.Threading.Tasks; 3 | using WorkLifeBalance.ViewModels.Base; 4 | 5 | namespace WorkLifeBalance.ViewModels 6 | { 7 | public abstract partial class SecondWindowPageVMBase : PageViewModelBase 8 | { 9 | [ObservableProperty] 10 | private double pageWidth = 250; 11 | 12 | [ObservableProperty] 13 | private double pageHeight = 300; 14 | 15 | [ObservableProperty] 16 | private string pageName = "Page"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ViewModels/Base/PageViewModelBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.ViewModels.Base 8 | { 9 | public class PageViewModelBase : ViewModelBase 10 | { 11 | public virtual Task OnPageClosingAsync() 12 | { 13 | return Task.CompletedTask; 14 | } 15 | 16 | public virtual Task OnPageOppeningAsync(object? args = null) 17 | { 18 | return Task.CompletedTask; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /Views/ViewDaysPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Windows; 6 | using System.Windows.Controls; 7 | using System.Windows.Media; 8 | using WorkLifeBalance.Models; 9 | using WorkLifeBalance.ViewModels; 10 | 11 | namespace WorkLifeBalance.Views 12 | { 13 | /// 14 | /// Interaction logic for ViewDaysPage.xaml 15 | /// 16 | public partial class ViewDaysPage : Page 17 | { 18 | public ViewDaysPage() 19 | { 20 | InitializeComponent(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Services/NavigationService.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System; 3 | using WorkLifeBalance.Interfaces; 4 | using WorkLifeBalance.ViewModels.Base; 5 | 6 | namespace WorkLifeBalance.Services 7 | { 8 | public partial class NavigationService : INavigationService 9 | { 10 | 11 | private readonly Func _viewModelFactory; 12 | 13 | public NavigationService(Func viewModelFactory) 14 | { 15 | _viewModelFactory = viewModelFactory; 16 | } 17 | 18 | public ViewModelBase NavigateTo() where TViewModelbase : ViewModelBase 19 | { 20 | return _viewModelFactory.Invoke(typeof(TViewModelbase)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Views/UpdatePage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WorkLifeBalance.Views 17 | { 18 | /// 19 | /// Interaction logic for UpdatePage.xaml 20 | /// 21 | public partial class UpdatePage : Page 22 | { 23 | public UpdatePage() 24 | { 25 | InitializeComponent(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Views/LoadingPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WorkLifeBalance.Views 17 | { 18 | /// 19 | /// Interaction logic for LoadingPage.xaml 20 | /// 21 | public partial class LoadingPage : Page 22 | { 23 | public LoadingPage() 24 | { 25 | InitializeComponent(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Converters/NullToVisibilityConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Windows.Data; 8 | using System.Windows; 9 | 10 | namespace WorkLifeBalance.Converters 11 | { 12 | public class NullToVisibilityConverter : IValueConverter 13 | { 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return value == null ? Visibility.Collapsed : Visibility.Visible; 17 | } 18 | 19 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 20 | { 21 | return value; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Views/ForceWorkMainMenuDetailsPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WorkLifeBalance.Views 17 | { 18 | /// 19 | /// Interaction logic for ForceWorkMainMenuDetailsPage.xaml 20 | /// 21 | public partial class ForceWorkMainMenuDetailsPage : Page 22 | { 23 | public ForceWorkMainMenuDetailsPage() 24 | { 25 | InitializeComponent(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Converters/IntToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace WorkLifeBalance.Converters 6 | { 7 | public class IntToStringConverter : IValueConverter 8 | { 9 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 10 | { 11 | if (value is int intValue) 12 | { 13 | return intValue.ToString(); 14 | } 15 | return string.Empty; 16 | } 17 | 18 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 19 | { 20 | if (int.TryParse(value as string, out int result)) 21 | { 22 | return result; 23 | } 24 | return 0; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Views/ForceStateMainMenuDetailsPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WorkLifeBalance.Views 17 | { 18 | /// 19 | /// Interaction logic for ForceStateMainMenuDetailsPage.xaml 20 | /// 21 | public partial class ForceStateMainMenuDetailsPage : Page 22 | { 23 | public ForceStateMainMenuDetailsPage() 24 | { 25 | InitializeComponent(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Views/ForceWorkPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows; 7 | using System.Windows.Controls; 8 | using System.Windows.Data; 9 | using System.Windows.Documents; 10 | using System.Windows.Input; 11 | using System.Windows.Media; 12 | using System.Windows.Media.Imaging; 13 | using System.Windows.Navigation; 14 | using System.Windows.Shapes; 15 | 16 | namespace WorkLifeBalance.Views 17 | { 18 | /// 19 | /// Interaction logic for ForceWorkPage.xaml 20 | /// 21 | public partial class ForceWorkPage : Page 22 | { 23 | public ForceWorkPage() 24 | { 25 | InitializeComponent(); 26 | } 27 | 28 | private void StackPanel_GotFocus(object sender, RoutedEventArgs e) 29 | { 30 | 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ViewModels/SecondWindowVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using WorkLifeBalance.Interfaces; 5 | 6 | namespace WorkLifeBalance.ViewModels 7 | { 8 | public partial class SecondWindowVM : ObservableObject 9 | { 10 | public ISecondWindowService SecondWindowService { get; set; } 11 | 12 | public Action? OnShowView { get; set; } = new(() => { }); 13 | public Action? OnHideView { get; set; } = new(() => { }); 14 | 15 | public SecondWindowVM(ISecondWindowService secondWindowService) 16 | { 17 | this.SecondWindowService = secondWindowService; 18 | SecondWindowService.OnPageLoaded += () => { OnShowView?.Invoke(); }; 19 | } 20 | 21 | [RelayCommand] 22 | private void CloseSecondWindow() 23 | { 24 | SecondWindowService.CloseWindow(); 25 | OnHideView?.Invoke(); 26 | } 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Services/AppStateHandler.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.Threading.Channels; 4 | using WorkLifeBalance.Services.Feature; 5 | 6 | namespace WorkLifeBalance.Services 7 | { 8 | public class AppStateHandler 9 | { 10 | public event Action? OnStateChanges; 11 | 12 | private AppState appTimerState = AppState.Resting; 13 | public AppState AppTimerState 14 | { 15 | get 16 | { 17 | return appTimerState; 18 | } 19 | set 20 | { 21 | if (appTimerState == value) return; 22 | appTimerState = value; 23 | OnStateChanges?.Invoke(appTimerState); 24 | } 25 | } 26 | 27 | public void SetAppState(AppState state) 28 | { 29 | if (AppTimerState == state) return; 30 | 31 | AppTimerState = state; 32 | Log.Information($"App state changed to {state}"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Converters/BoolToVisibleConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows; 4 | using System.Windows.Data; 5 | 6 | namespace WorkLifeBalance.Converters 7 | { 8 | public class BoolToVisibleConverter : IValueConverter 9 | { 10 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 11 | { 12 | if (value is bool enabled) 13 | { 14 | return enabled == true ? Visibility.Visible : Visibility.Collapsed; 15 | } 16 | 17 | throw new Exception("Value is not of type bool"); 18 | } 19 | 20 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 21 | { 22 | if (value is Visibility visible) 23 | { 24 | return visible == Visibility.Visible ? true : false; 25 | } 26 | 27 | throw new Exception("Value is not of type Visibility"); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /SecondWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Threading.Tasks; 4 | using System.Windows; 5 | using System.Windows.Input; 6 | using WorkLifeBalance.ViewModels; 7 | 8 | namespace WorkLifeBalance 9 | { 10 | /// 11 | /// Interaction logic for SecondWindow.xaml 12 | /// 13 | /// //use it in dependency injection, make searate method for req windows 14 | public partial class SecondWindow : Window 15 | { 16 | private readonly SecondWindowVM ViewModel; 17 | 18 | public SecondWindow(SecondWindowVM viewModel) 19 | { 20 | Topmost = true; 21 | ViewModel = viewModel; 22 | DataContext = ViewModel; 23 | ViewModel.OnShowView += Show; 24 | ViewModel.OnHideView += Hide; 25 | InitializeComponent(); 26 | } 27 | 28 | private void MoveWindow(object sender, MouseButtonEventArgs e) 29 | { 30 | if (e.LeftButton == MouseButtonState.Pressed) 31 | { 32 | DragMove(); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Converters/BoolToCollapsedConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | using System.Windows.Data; 9 | 10 | namespace WorkLifeBalance.Converters 11 | { 12 | public class BoolToCollapsedConverter : IValueConverter 13 | { 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value is bool enabled) 17 | { 18 | return enabled == true ? Visibility.Collapsed : Visibility.Visible; 19 | } 20 | 21 | throw new Exception("Value is not of type bool"); 22 | } 23 | 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value is Visibility visible) 27 | { 28 | return visible == Visibility.Visible ? false : true; 29 | } 30 | 31 | throw new Exception("Value is not of type Visibility"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Szabo Robert Casian 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /WorkLifeBalance.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33414.496 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WorkLifeBalance", "WorkLifeBalance.csproj", "{F08B0D42-CD5E-4BB7-8DAA-C078FD777226}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {F08B0D42-CD5E-4BB7-8DAA-C078FD777226}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {F08B0D42-CD5E-4BB7-8DAA-C078FD777226}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {F08B0D42-CD5E-4BB7-8DAA-C078FD777226}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {F08B0D42-CD5E-4BB7-8DAA-C078FD777226}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {09C846F7-68CC-4BEA-8FC3-FBB83D3A71B4} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Converters/DateOnlyToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace WorkLifeBalance.Converters 6 | { 7 | public class DateOnlyToStringConverter : IValueConverter 8 | { 9 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 10 | { 11 | if (value is DateOnly date) 12 | { 13 | return date.ToString("MM/dd/yyyy"); 14 | } 15 | throw new Exception("Value is not of type DateOnly"); 16 | } 17 | 18 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 19 | { 20 | if(value is string date) 21 | { 22 | DateOnly newDate = DateOnly.MinValue; 23 | string[] dateData = date.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries); 24 | newDate = new 25 | ( 26 | int.Parse(dateData[2]), 27 | int.Parse(dateData[0]), 28 | int.Parse(dateData[1]) 29 | ); 30 | return newDate; 31 | } 32 | throw new Exception("Value is not of type string"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ViewModels/CloseWarningPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.Input; 2 | using Serilog; 3 | using System.Threading.Tasks; 4 | using System.Windows; 5 | using WorkLifeBalance.Services.Feature; 6 | 7 | namespace WorkLifeBalance.ViewModels 8 | { 9 | public partial class CloseWarningPageVM : SecondWindowPageVMBase 10 | { 11 | private readonly DataStorageFeature dataStorageFeature; 12 | public CloseWarningPageVM(DataStorageFeature dataStorageFeature) 13 | { 14 | PageHeight = 160; 15 | PageWidth = 280; 16 | PageName = "Close Warning"; 17 | this.dataStorageFeature = dataStorageFeature; 18 | } 19 | 20 | [RelayCommand] 21 | private void CloseApp() 22 | { 23 | if (dataStorageFeature.IsClosingApp) return; 24 | 25 | dataStorageFeature.IsClosingApp = true; 26 | 27 | Log.Information("------------------App Shuting Down------------------"); 28 | 29 | _ = Task.Run(async () => 30 | { 31 | await dataStorageFeature.SaveData(); 32 | await Log.CloseAndFlushAsync(); 33 | 34 | App.Current.Dispatcher.Invoke(() => 35 | { 36 | Application.Current.Shutdown(); 37 | }); 38 | }); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Services/SoundService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using WorkLifeBalance.Interfaces; 7 | using System.Windows.Media; 8 | using System.DirectoryServices; 9 | 10 | namespace WorkLifeBalance.Services 11 | { 12 | public class SoundService : ISoundService 13 | { 14 | private Dictionary Sounds = new(); 15 | 16 | public SoundService() 17 | { 18 | MediaPlayer Warning = new(); 19 | Warning.Open(new Uri("Assets/Sounds/Error.mp3", UriKind.Relative)); 20 | 21 | MediaPlayer Termination = new(); 22 | Termination.Open(new Uri("Assets/Sounds/Termination.mp3", UriKind.Relative)); 23 | 24 | MediaPlayer Finish = new(); 25 | Finish.Open(new Uri("Assets/Sounds/Finish.mp3", UriKind.Relative)); 26 | 27 | Sounds.Add(ISoundService.SoundType.Warning, Warning); 28 | Sounds.Add(ISoundService.SoundType.Termination, Termination); 29 | Sounds.Add(ISoundService.SoundType.Finish, Finish); 30 | } 31 | 32 | public void PlaySound(ISoundService.SoundType type) 33 | { 34 | MediaPlayer activeSound = Sounds[type]; 35 | activeSound.Position = TimeSpan.Zero; 36 | activeSound.Play(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Views/LoadingPage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Services/FeaturesService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using WorkLifeBalance.Interfaces; 3 | using WorkLifeBalance.Services.Feature; 4 | using WorkLifeBalance.ViewModels; 5 | 6 | namespace WorkLifeBalance.Services 7 | { 8 | public class FeaturesService : IFeaturesServices 9 | { 10 | private readonly Func _featureFactory; 11 | private readonly AppTimer _appTimer; 12 | public FeaturesService(Func featureFactory, AppTimer appTimer) 13 | { 14 | _featureFactory = featureFactory; 15 | _appTimer = appTimer; 16 | } 17 | 18 | public void AddFeature() where TFeature : FeatureBase 19 | { 20 | if (IsFeaturePresent()) return; 21 | FeatureBase feature = _featureFactory.Invoke(typeof(TFeature)); 22 | _appTimer.Subscribe(feature.AddFeature()); 23 | } 24 | 25 | public bool IsFeaturePresent() where TFeature : FeatureBase 26 | { 27 | FeatureBase feature = _featureFactory.Invoke(typeof(TFeature)); 28 | return _appTimer.IsFeaturePresent(feature.GetFeature()); 29 | } 30 | 31 | public void RemoveFeature() where TFeature : FeatureBase 32 | { 33 | if (!IsFeaturePresent()) return; 34 | FeatureBase feature = _featureFactory.Invoke(typeof(TFeature)); 35 | _appTimer.UnSubscribe(feature.RemoveFeature()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Converters/TimeOnlyToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace WorkLifeBalance.Converters 6 | { 7 | public class TimeOnlyToStringConverter : IValueConverter 8 | { 9 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 10 | { 11 | if (value is TimeOnly time) 12 | { 13 | return time.ToString("HH:mm:ss"); 14 | } 15 | throw new Exception("Value is not of type TimeOnly"); 16 | } 17 | 18 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 19 | { 20 | if (value is string time) 21 | { 22 | TimeOnly newTime = TimeOnly.MinValue; 23 | string[] timeData = time.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); 24 | Console.WriteLine(timeData.Length); 25 | foreach(string timer in timeData) 26 | { 27 | Console.WriteLine(timer); 28 | } 29 | newTime = new 30 | ( 31 | int.Parse(timeData[0]), 32 | int.Parse(timeData[1]), 33 | int.Parse(timeData[2]) 34 | ); 35 | return newTime; 36 | } 37 | throw new Exception("Value is not of type string"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Views/CloseWarningPage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 13 | 14 | 20 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Views/UpdatePage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 14 | 15 | 16 | 19 | 20 | 21 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /ViewModels/OptionsPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.Input; 2 | using WorkLifeBalance.Interfaces; 3 | using WorkLifeBalance.Services; 4 | 5 | namespace WorkLifeBalance.ViewModels 6 | { 7 | public partial class OptionsPageVM : SecondWindowPageVMBase 8 | { 9 | private readonly ISecondWindowService secondWindowService; 10 | private readonly LowLevelHandler LowLevelHandler; 11 | public OptionsPageVM(ISecondWindowService secondWindowService, LowLevelHandler lowLevelHandler) 12 | { 13 | this.secondWindowService = secondWindowService; 14 | PageHeight = 320; 15 | PageWidth = 250; 16 | PageName = "Options"; 17 | LowLevelHandler = lowLevelHandler; 18 | } 19 | 20 | [RelayCommand] 21 | private void OpenSettings() 22 | { 23 | secondWindowService.OpenWindowWith(); 24 | } 25 | 26 | [RelayCommand] 27 | private void ConfigureAutoDetect() 28 | { 29 | secondWindowService.OpenWindowWith(); 30 | } 31 | 32 | [RelayCommand] 33 | private void OpenDonations() 34 | { 35 | LowLevelHandler.OpenLink("https://buymeacoffee.com/RoberBot"); 36 | } 37 | 38 | [RelayCommand] 39 | private void OpenFeedback() 40 | { 41 | 42 | LowLevelHandler.OpenLink(@"https://docs.google.com/forms/d/e/1FAIpQLSfkPDHOLysWAPLZc9pdLFyRmiFxlVBN0xefXFcZ7XACOnnPhw/viewform?usp=sf_link"); 43 | } 44 | 45 | [RelayCommand] 46 | private void OpenForceWork() 47 | { 48 | secondWindowService.OpenWindowWith(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ViewModels/UpdatePageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using Serilog; 4 | using System.Diagnostics; 5 | using System.Threading.Tasks; 6 | using WorkLifeBalance.Models; 7 | using WorkLifeBalance.Services; 8 | 9 | namespace WorkLifeBalance.ViewModels 10 | { 11 | public partial class UpdatePageVM : SecondWindowPageVMBase 12 | { 13 | [ObservableProperty] 14 | private string version = "Error"; 15 | 16 | [ObservableProperty] 17 | private string updateLog = "Error"; 18 | 19 | private VersionData? Vdata; 20 | private readonly LowLevelHandler lowLevelHandler; 21 | public UpdatePageVM(LowLevelHandler lowLevelHandler) 22 | { 23 | this.lowLevelHandler = lowLevelHandler; 24 | PageName = "Update Available"; 25 | PageHeight = 400; 26 | PageWidth = 350; 27 | } 28 | 29 | public override Task OnPageOppeningAsync(object? args = null) 30 | { 31 | if (args is VersionData data) 32 | { 33 | Vdata = data; 34 | 35 | Version = $"New Version: {Vdata.Version!}"; 36 | UpdateLog = Vdata.UpdateLog!; 37 | } 38 | else 39 | { 40 | Log.Error("UpdatePageVm oppened with wrong arguments, args != VersionData"); 41 | } 42 | 43 | return Task.CompletedTask; 44 | } 45 | 46 | [RelayCommand] 47 | private void GoToDownload() 48 | { 49 | if(Vdata != null) 50 | { 51 | lowLevelHandler.OpenLink(Vdata.DownloadLink!); 52 | App.Current.Shutdown(); 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Services/Feature/TimeTrackerFeature.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace WorkLifeBalance.Services.Feature 5 | { 6 | public class TimeTrackerFeature : FeatureBase 7 | { 8 | public delegate void SpentTimeEvent(); 9 | public event SpentTimeEvent? OnSpentTimeChange; 10 | 11 | private readonly TimeSpan OneSec = new (0, 0, 1); 12 | private readonly AppStateHandler appStateHandler; 13 | private readonly DataStorageFeature dataStorageFeature; 14 | public TimeTrackerFeature(DataStorageFeature dataStorageFeature, AppStateHandler appStateHandler) 15 | { 16 | this.dataStorageFeature = dataStorageFeature; 17 | this.appStateHandler = appStateHandler; 18 | } 19 | 20 | protected override Func ReturnFeatureMethod() 21 | { 22 | return TriggerUpdateSpentTime; 23 | } 24 | 25 | private Task TriggerUpdateSpentTime() 26 | { 27 | switch (appStateHandler.AppTimerState) 28 | { 29 | case AppState.Working: 30 | dataStorageFeature.TodayData.WorkedAmmountC = dataStorageFeature.TodayData.WorkedAmmountC.Add(OneSec); 31 | break; 32 | 33 | case AppState.Resting: 34 | dataStorageFeature.TodayData.RestedAmmountC = dataStorageFeature.TodayData.RestedAmmountC.Add(OneSec); 35 | break; 36 | 37 | case AppState.Idle: 38 | dataStorageFeature.TodayData.IdleAmmountC = dataStorageFeature.TodayData.IdleAmmountC.Add(OneSec); 39 | break; 40 | } 41 | OnSpentTimeChange?.Invoke(); 42 | return Task.CompletedTask; 43 | } 44 | } 45 | 46 | public enum AppState 47 | { 48 | Working, 49 | Resting, 50 | Idle 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Services/MainWindowDetailsService.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WorkLifeBalance.Interfaces; 8 | using WorkLifeBalance.ViewModels; 9 | using WorkLifeBalance.ViewModels.Base; 10 | 11 | namespace WorkLifeBalance.Services 12 | { 13 | public partial class MainWindowDetailsService : ObservableObject, IMainWindowDetailsService 14 | { 15 | //needs a way to stop multiple features requesting a MainWindowDetails page. 16 | private INavigationService navigationService; 17 | 18 | [ObservableProperty] 19 | private MainWindowDetailsPageBase? loadedPage; 20 | 21 | private MainWindowDetailsPageBase? activeMainWindowPage; 22 | 23 | public MainWindowDetailsService(INavigationService navigationService) 24 | { 25 | this.navigationService = navigationService; 26 | } 27 | 28 | public void CloseWindow() 29 | { 30 | _ = Task.Run(ClearPage); 31 | } 32 | 33 | private async Task ClearPage() 34 | { 35 | if (LoadedPage != null) 36 | { 37 | await LoadedPage.OnPageClosingAsync(); 38 | LoadedPage = null; 39 | } 40 | } 41 | 42 | public async Task OpenDetailsPageWith(object? args) where T : MainWindowDetailsPageBase 43 | { 44 | await Task.Run(ClearPage); 45 | 46 | activeMainWindowPage = (MainWindowDetailsPageBase)navigationService.NavigateTo(); 47 | 48 | await Task.Run(async () => 49 | { 50 | await activeMainWindowPage.OnPageOppeningAsync(args); 51 | App.Current.Dispatcher.Invoke(() => 52 | { 53 | LoadedPage = activeMainWindowPage; 54 | }); 55 | }); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Models/ProcessActivityData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WorkLifeBalance.Models 4 | { 5 | [Serializable] 6 | public class ProcessActivityData 7 | { 8 | public string Date { get; set; } = "06062023"; 9 | public string Process { get; set; } = "da"; 10 | public string TimeSpent { get; set; } = "000000"; 11 | 12 | public DateOnly DateC { get; set; } = DateOnly.FromDateTime(DateTime.Now); 13 | public TimeOnly TimeSpentC { get; set; } = new TimeOnly(0, 0, 0); 14 | 15 | public void ConvertSaveDataToUsableData() 16 | { 17 | try 18 | { 19 | if (string.IsNullOrEmpty(Date)) 20 | { 21 | return; 22 | } 23 | 24 | DateC = new DateOnly 25 | ( 26 | int.Parse(Date.Substring(4, 4)), 27 | int.Parse(Date.Substring(0, 2)), 28 | int.Parse(Date.Substring(2, 2)) 29 | ); 30 | 31 | TimeSpentC = new TimeOnly 32 | ( 33 | int.Parse(TimeSpent.Substring(0, 2)), 34 | int.Parse(TimeSpent.Substring(2, 2)), 35 | int.Parse(TimeSpent.Substring(4, 2)) 36 | ); 37 | } 38 | catch (Exception ex) 39 | { 40 | //MainWindow.ShowErrorBox("ProcessActivity Error", "Failed to convert data to usable data", ex); 41 | } 42 | } 43 | public void ConvertUsableDataToSaveData() 44 | { 45 | try 46 | { 47 | Date = DateC.ToString("MMddyyyy"); 48 | 49 | TimeSpent = TimeSpentC.ToString("HHmmss"); 50 | } 51 | catch (Exception ex) 52 | { 53 | //MainWindow.ShowErrorBox("ProcessActivity Error", "Failed to convert usable data to save data", ex); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /ViewModels/ForceStateMainMenuDetailsPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using System.Threading.Tasks; 5 | using WorkLifeBalance.Interfaces; 6 | using WorkLifeBalance.Services.Feature; 7 | using WorkLifeBalance.ViewModels.Base; 8 | 9 | namespace WorkLifeBalance.ViewModels 10 | { 11 | public partial class ForceStateMainMenuDetailsPageVM : MainWindowDetailsPageBase 12 | { 13 | [ObservableProperty] 14 | private AppState forcedAppState = AppState.Resting; 15 | 16 | private readonly IFeaturesServices featuresServices; 17 | private readonly ForceStateFeature forceStateFeature; 18 | 19 | private int AppstatesCount; 20 | public ForceStateMainMenuDetailsPageVM(ForceStateFeature forceStateFeature, IFeaturesServices featuresServices) 21 | { 22 | this.forceStateFeature = forceStateFeature; 23 | this.featuresServices = featuresServices; 24 | AppstatesCount = Enum.GetValues(typeof(AppState)).Length - 1; 25 | } 26 | 27 | partial void OnForcedAppStateChanged(AppState value) 28 | { 29 | forceStateFeature.SetForcedAppState(value); 30 | } 31 | 32 | [RelayCommand] 33 | private void ChangeForcedState() 34 | { 35 | if((int)ForcedAppState == AppstatesCount) 36 | { 37 | ForcedAppState = 0; 38 | } 39 | else 40 | { 41 | ForcedAppState++; 42 | } 43 | } 44 | 45 | public override Task OnPageOppeningAsync(object? args = null) 46 | { 47 | 48 | forceStateFeature.SetForcedAppState(ForcedAppState); 49 | return base.OnPageOppeningAsync(args); 50 | } 51 | 52 | public override Task OnPageClosingAsync() 53 | { 54 | featuresServices.RemoveFeature(); 55 | return base.OnPageClosingAsync(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Services/Feature/ActivityTrackerFeature.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.Threading.Tasks; 4 | 5 | namespace WorkLifeBalance.Services.Feature 6 | { 7 | public class ActivityTrackerFeature : FeatureBase 8 | { 9 | public delegate void ActiveProcess(string ActiveWindow); 10 | public event ActiveProcess? OnWindowChange; 11 | 12 | public string ActiveWindow { get; set; } = ""; 13 | 14 | private readonly TimeSpan OneSec = new (0, 0, 1); 15 | 16 | private readonly LowLevelHandler lowLevelHandler; 17 | private readonly DataStorageFeature dataStorageFeature; 18 | public ActivityTrackerFeature(LowLevelHandler lowLevelHandler, DataStorageFeature dataStorageFeature) 19 | { 20 | this.lowLevelHandler = lowLevelHandler; 21 | this.dataStorageFeature = dataStorageFeature; 22 | } 23 | 24 | protected override Func ReturnFeatureMethod() 25 | { 26 | return TriggerRecordActivity; 27 | } 28 | 29 | private Task TriggerRecordActivity() 30 | { 31 | try 32 | { 33 | nint foregroundWindowHandle = lowLevelHandler.ReadForegroundWindow(); 34 | 35 | ActiveWindow = lowLevelHandler.GetProcessname(foregroundWindowHandle); 36 | OnWindowChange?.Invoke(ActiveWindow); 37 | } 38 | catch (Exception ex) 39 | { 40 | Log.Warning(ex, "Failed to get process of window"); 41 | } 42 | 43 | try 44 | { 45 | TimeOnly IncreasedTimeSpan = dataStorageFeature.AutoChangeData.ActivitiesC[ActiveWindow].Add(OneSec); 46 | dataStorageFeature.AutoChangeData.ActivitiesC[ActiveWindow] = IncreasedTimeSpan; 47 | } 48 | catch 49 | { 50 | dataStorageFeature.AutoChangeData.ActivitiesC.Add(ActiveWindow, new TimeOnly()); 51 | } 52 | return Task.CompletedTask; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Services/Feature/FeatureBase.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System; 3 | using System.Security.AccessControl; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace WorkLifeBalance.Services.Feature 8 | { 9 | public abstract class FeatureBase 10 | { 11 | //base class for every feature, it cancels the feature delay if feature removed. 12 | //features use a bool to ignore the main timer event when the feature was triggered 13 | //if the main timer runs every second and a feature has a 5 minute trigger interval 14 | //it will run once then ignore the main timer for 5 minutes and repeat. 15 | protected CancellationTokenSource CancelTokenS { get; set; } = new(); 16 | 17 | public bool IsFeatureRuning { get; set; } 18 | 19 | //used to add the current feature and create a new canceltoken,returns overrided method 20 | public Func AddFeature() 21 | { 22 | IsFeatureRuning = false; 23 | CancelTokenS = new(); 24 | OnFeatureAdded(); 25 | return ReturnFeatureMethod(); 26 | } 27 | 28 | //get the method 29 | public Func GetFeature() 30 | { 31 | return ReturnFeatureMethod(); 32 | } 33 | 34 | //used to remove the feature, cancels the features and returns the specific method 35 | //that needs to be removed from main timer 36 | public Func RemoveFeature() 37 | { 38 | CancelToken(); 39 | OnFeatureRemoved(); 40 | return ReturnFeatureMethod(); 41 | } 42 | 43 | //override in childrens to return the feature specific main method 44 | protected abstract Func ReturnFeatureMethod(); 45 | 46 | protected virtual void OnFeatureAdded() { } 47 | protected virtual void OnFeatureRemoved() { } 48 | 49 | private void CancelToken() 50 | { 51 | CancelTokenS.Cancel(); 52 | CancelTokenS = new(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Models/AutoStateChangeData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace WorkLifeBalance.Models 5 | { 6 | [Serializable] 7 | public class AutoStateChangeData 8 | { 9 | public ProcessActivityData[] Activities { get; set; } = Array.Empty(); 10 | public string[] WorkingStateWindows { get; set; } = Array.Empty(); 11 | 12 | public Dictionary ActivitiesC = new(); 13 | 14 | public void ConvertSaveDataToUsableData() 15 | { 16 | try 17 | { 18 | foreach (ProcessActivityData activity in Activities) 19 | { 20 | activity.ConvertSaveDataToUsableData(); 21 | ActivitiesC.Add(activity.Process, activity.TimeSpentC); 22 | } 23 | } 24 | catch (Exception ex) 25 | { 26 | //MainWindow.ShowErrorBox("StateChangeData Error", "Failed to convert data to usable data", ex); 27 | } 28 | } 29 | public void ConvertUsableDataToSaveData() 30 | { 31 | try 32 | { 33 | List processActivities = new(); 34 | 35 | 36 | foreach (KeyValuePair activity in ActivitiesC) 37 | { 38 | ProcessActivityData process = new() 39 | { 40 | //process.DateC = DataStorageFeature.Instance.TodayData.DateC; 41 | Process = activity.Key, 42 | TimeSpentC = activity.Value 43 | }; 44 | 45 | process.ConvertUsableDataToSaveData(); 46 | 47 | processActivities.Add(process); 48 | } 49 | 50 | Activities = processActivities.ToArray(); 51 | } 52 | catch (Exception ex) 53 | { 54 | //MainWindow.ShowErrorBox("StateChangeData Error", "Failed to convert usable data to save data", ex); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Style/PageVMBindings.xaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Services/Feature/ForceStateFeature.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using WorkLifeBalance.Interfaces; 4 | using WorkLifeBalance.ViewModels; 5 | 6 | namespace WorkLifeBalance.Services.Feature 7 | { 8 | public class ForceStateFeature : FeatureBase 9 | { 10 | private readonly IMainWindowDetailsService mainWindowDetailsService; 11 | private readonly DataStorageFeature dataStorageFeature; 12 | private readonly IFeaturesServices featuresServices; 13 | private readonly AppStateHandler appStateHandler; 14 | public ForceStateFeature(IMainWindowDetailsService mainWindowDetailsService, DataStorageFeature dataStorageFeature, IFeaturesServices featuresServices, AppStateHandler appStateHandler) 15 | { 16 | this.mainWindowDetailsService = mainWindowDetailsService; 17 | this.dataStorageFeature = dataStorageFeature; 18 | this.featuresServices = featuresServices; 19 | this.appStateHandler = appStateHandler; 20 | } 21 | 22 | protected override void OnFeatureAdded() 23 | { 24 | featuresServices.RemoveFeature(); 25 | featuresServices.RemoveFeature(); 26 | 27 | dataStorageFeature.Settings.IsForceStateActive = true; 28 | mainWindowDetailsService.OpenDetailsPageWith(); 29 | } 30 | 31 | public void SetForcedAppState(AppState state) 32 | { 33 | appStateHandler.SetAppState(state); 34 | } 35 | 36 | protected override void OnFeatureRemoved() 37 | { 38 | featuresServices.AddFeature(); 39 | featuresServices.AddFeature(); 40 | 41 | dataStorageFeature.Settings.IsForceStateActive = false; 42 | mainWindowDetailsService.CloseWindow(); 43 | } 44 | 45 | protected override Func ReturnFeatureMethod() 46 | { 47 | return ForceStateMethod; 48 | } 49 | 50 | private Task ForceStateMethod() 51 | { 52 | return Task.CompletedTask; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Windows; 4 | using System.Windows.Forms; 5 | using System.Windows.Input; 6 | using WorkLifeBalance.ViewModels; 7 | 8 | namespace WorkLifeBalance 9 | { 10 | /// 11 | /// Interaction logic for MainWindow.xaml 12 | /// 13 | /// 14 | public partial class MainWindow : Window, IDisposable 15 | { 16 | private readonly MainWindowVM ViewModel; 17 | private readonly NotifyIcon NotifyIcon; 18 | 19 | public MainWindow(MainWindowVM viewModel) 20 | { 21 | Topmost = true; 22 | ViewModel = viewModel; 23 | DataContext = viewModel; 24 | NotifyIcon = new NotifyIcon 25 | { 26 | Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location) 27 | }; 28 | NotifyIcon.Click += OnNotifyIconOnClick; 29 | SetStartUpLocation(); 30 | InitializeComponent(); 31 | } 32 | 33 | private void SetStartUpLocation() 34 | { 35 | int ScreenHeight = (int)SystemParameters.PrimaryScreenHeight; 36 | Left = 0; 37 | Top = ScreenHeight - 297; 38 | } 39 | 40 | private void MoveWindow(object sender, MouseButtonEventArgs e) 41 | { 42 | if (e.LeftButton == MouseButtonState.Pressed) 43 | { 44 | DragMove(); 45 | } 46 | } 47 | 48 | private void OnNotifyIconOnClick(object? sender, EventArgs args) 49 | { 50 | Show(); 51 | WindowState = WindowState.Normal; 52 | NotifyIcon.Visible = false; 53 | } 54 | 55 | private void HideWindow(object sender, RoutedEventArgs e) 56 | { 57 | if (ViewModel.MinimizeToTray) 58 | { 59 | Hide(); 60 | NotifyIcon.Visible = true; 61 | } 62 | else 63 | { 64 | WindowState = WindowState.Minimized; 65 | } 66 | } 67 | 68 | public void Dispose() 69 | { 70 | NotifyIcon.Dispose(); 71 | GC.SuppressFinalize(this); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Style/Colors.xaml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | #1a1631 7 | #1d1841 8 | #28234c 9 | 10 | #2e2a4a 11 | #363062 12 | #484274 13 | 14 | #3b4665 15 | #435585 16 | #5c6e9e 17 | 18 | #637095 19 | #818FB4 20 | #b5bbce 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /ViewModels/ViewDayDetailsPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using WorkLifeBalance.Interfaces; 8 | using WorkLifeBalance.Models; 9 | using WorkLifeBalance.Services; 10 | 11 | namespace WorkLifeBalance.ViewModels 12 | { 13 | public partial class ViewDayDetailsPageVM : SecondWindowPageVMBase 14 | { 15 | [ObservableProperty] 16 | private ProcessActivityData[]? activities; 17 | 18 | [ObservableProperty] 19 | private DayData? loadedDayData; 20 | 21 | private int LoadedPageType; 22 | private ISecondWindowService secondWindowService; 23 | private DataBaseHandler database; 24 | public ViewDayDetailsPageVM(ISecondWindowService secondWindowService, DataBaseHandler database) 25 | { 26 | PageHeight = 440; 27 | PageWidth = 430; 28 | PageName = "View Day Details"; 29 | this.secondWindowService = secondWindowService; 30 | this.database = database; 31 | } 32 | 33 | private async Task RequiestData() 34 | { 35 | List RequestedActivity = (await database.ReadDayActivity(LoadedDayData!.Date)); 36 | Activities = RequestedActivity.OrderByDescending(data => data.TimeSpentC).ToArray(); 37 | } 38 | 39 | public override Task OnPageOppeningAsync(object? args) 40 | { 41 | if (args != null) 42 | { 43 | if (args is (int loadedpagetype, DayData day)) 44 | { 45 | LoadedPageType = loadedpagetype; 46 | LoadedDayData = day; 47 | PageName = $"{LoadedDayData.DateC.ToString("MM/dd/yyyy")} Activity"; 48 | _ = RequiestData(); 49 | return base.OnPageOppeningAsync(args); 50 | } 51 | } 52 | 53 | //MainWindow.ShowErrorBox("Error ViewDayDetails", "Requested ViewDayDetails Page with no/wrong arguments"); 54 | return base.OnPageOppeningAsync(args); 55 | } 56 | 57 | [RelayCommand] 58 | private void BackToViewDaysPage() 59 | { 60 | secondWindowService.OpenWindowWith(LoadedPageType); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /ViewModels/ForceWorkMainMenuDetailsPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using WorkLifeBalance.Interfaces; 9 | using WorkLifeBalance.Services.Feature; 10 | using WorkLifeBalance.ViewModels.Base; 11 | 12 | namespace WorkLifeBalance.ViewModels 13 | { 14 | public partial class ForceWorkMainMenuDetailsPageVM : MainWindowDetailsPageBase 15 | { 16 | 17 | [ObservableProperty] 18 | private AppState requiredAppState; 19 | 20 | [ObservableProperty] 21 | private TimeOnly currentStageTimeRemaining; 22 | 23 | [ObservableProperty] 24 | private TimeOnly totalWorkTimeRemaining; 25 | 26 | private readonly ForceWorkFeature forceWorkFeature; 27 | private readonly ISecondWindowService secondWindowService; 28 | private readonly IFeaturesServices featuresServices; 29 | 30 | public ForceWorkMainMenuDetailsPageVM(ForceWorkFeature forceWorkFeature, ISecondWindowService secondWindowService, IFeaturesServices featuresServices) 31 | { 32 | this.forceWorkFeature = forceWorkFeature; 33 | this.secondWindowService = secondWindowService; 34 | this.featuresServices = featuresServices; 35 | } 36 | 37 | public override Task OnPageOppeningAsync(object? args = null) 38 | { 39 | forceWorkFeature.OnDataUpdated += UpdateDataFromForceWork; 40 | UpdateDataFromForceWork(); 41 | return Task.CompletedTask; 42 | } 43 | 44 | public override Task OnPageClosingAsync() 45 | { 46 | forceWorkFeature.OnDataUpdated -= UpdateDataFromForceWork; 47 | featuresServices.RemoveFeature(); 48 | return Task.CompletedTask; 49 | } 50 | 51 | private void UpdateDataFromForceWork() 52 | { 53 | RequiredAppState = forceWorkFeature.RequiredAppState; 54 | CurrentStageTimeRemaining = forceWorkFeature.CurrentStageTimeRemaining; 55 | TotalWorkTimeRemaining = forceWorkFeature.TotalWorkTimeRemaining; 56 | } 57 | 58 | [RelayCommand] 59 | private void EditForceWork() 60 | { 61 | secondWindowService.OpenWindowWith(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /App.xaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Services/SecondWindowService.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System; 3 | using System.Threading.Tasks; 4 | using WorkLifeBalance.Interfaces; 5 | using WorkLifeBalance.Services.Feature; 6 | using WorkLifeBalance.ViewModels; 7 | 8 | namespace WorkLifeBalance.Services 9 | { 10 | public partial class SecondWindowService : ObservableObject, ISecondWindowService 11 | { 12 | private readonly INavigationService navigation; 13 | 14 | [ObservableProperty] 15 | private SecondWindowPageVMBase? loadedPage; 16 | private SecondWindowPageVMBase? activeSecondWindowPage; 17 | 18 | private readonly DataStorageFeature dataStorageFeature; 19 | public Action? OnPageLoaded { get; set; } = new(() => { }); 20 | 21 | partial void OnLoadedPageChanged(SecondWindowPageVMBase? oldValue, SecondWindowPageVMBase? newValue) 22 | { 23 | OnPageLoaded?.Invoke(); 24 | } 25 | 26 | public SecondWindowService(INavigationService navigation, DataStorageFeature dataStorageFeature) 27 | { 28 | this.navigation = navigation; 29 | this.dataStorageFeature = dataStorageFeature; 30 | } 31 | 32 | public void CloseWindow() 33 | { 34 | if (dataStorageFeature.IsClosingApp) return; 35 | _ = Task.Run(ClearPage); 36 | } 37 | 38 | private async Task ClearPage() 39 | { 40 | if(activeSecondWindowPage != null) 41 | { 42 | await activeSecondWindowPage.OnPageClosingAsync(); 43 | activeSecondWindowPage = null; 44 | } 45 | } 46 | 47 | public async Task OpenWindowWith(object? args = null) where T : SecondWindowPageVMBase 48 | { 49 | if (dataStorageFeature.IsClosingApp) return; 50 | 51 | SecondWindowPageVMBase loading = (SecondWindowPageVMBase)navigation.NavigateTo(); 52 | 53 | if(activeSecondWindowPage != null) 54 | { 55 | loading.PageWidth = activeSecondWindowPage.PageWidth; 56 | loading.PageHeight= activeSecondWindowPage.PageHeight; 57 | } 58 | 59 | LoadedPage = loading; 60 | 61 | await Task.Delay(150); 62 | 63 | await Task.Run(ClearPage); 64 | 65 | activeSecondWindowPage = (SecondWindowPageVMBase)navigation.NavigateTo(); 66 | 67 | await Task.Run(async () => 68 | { 69 | await activeSecondWindowPage.OnPageOppeningAsync(args); 70 | App.Current.Dispatcher.Invoke(() => 71 | { 72 | LoadedPage = activeSecondWindowPage; 73 | }); 74 | }); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Models/AppSettingsData.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using WorkLifeBalance.Services.Feature; 4 | 5 | namespace WorkLifeBalance.Models 6 | { 7 | public class AppSettingsData 8 | { 9 | public readonly string Version = "2.0.7"; 10 | public readonly string AppName = "WorkLifeBalance"; 11 | public string AppDirectory { get; set; } 12 | public string AppExePath { get; set; } 13 | public string LastTimeOpened { get; set; } = ""; 14 | public int SaveInterval { get; set; } = 5; 15 | public int AutoDetectInterval { get; set; } = 1; 16 | public int AutoDetectIdleInterval { get; set; } = 1; 17 | public int StartWithWindows { get; set; } 18 | public int MinimizeToTray { get; set; } 19 | 20 | public DateTime LastTimeOpenedC { get; set; } 21 | public bool StartWithWindowsC { get; set; } 22 | public bool MinimizeToTrayC { get; set; } 23 | 24 | public bool IsForceStateActive { get; set; } 25 | public AppState ForcedAppstate { get; set; } 26 | 27 | public Action OnSettingsChanged { get; set; } = new(() => { }); 28 | 29 | public AppSettingsData() 30 | { 31 | AppDirectory = AppDomain.CurrentDomain.BaseDirectory; 32 | AppExePath = @$"{AppDirectory}{AppName}.exe"; 33 | } 34 | 35 | public void ConvertSaveDataToUsableData() 36 | { 37 | try 38 | { 39 | if (!string.IsNullOrEmpty(LastTimeOpened)) 40 | { 41 | LastTimeOpenedC = new DateTime 42 | ( 43 | int.Parse(LastTimeOpened.Substring(8, 4)), 44 | int.Parse(LastTimeOpened.Substring(4, 2)), 45 | int.Parse(LastTimeOpened.Substring(6, 2)), 46 | int.Parse(LastTimeOpened.Substring(0, 2)), 47 | int.Parse(LastTimeOpened.Substring(2, 2)), 48 | 0 49 | ); 50 | } 51 | StartWithWindowsC = StartWithWindows == 1; 52 | MinimizeToTrayC = MinimizeToTray == 1; 53 | 54 | } 55 | catch (Exception ex) 56 | { 57 | Log.Error("AppSettings Error: Failed to convert data to usable data", ex); 58 | } 59 | 60 | } 61 | 62 | public void ConvertUsableDataToSaveData() 63 | { 64 | try 65 | { 66 | LastTimeOpenedC = DateTime.Now; 67 | LastTimeOpened = LastTimeOpenedC.ToString("HHmmMMddyyyy"); 68 | 69 | MinimizeToTray = MinimizeToTrayC ? 1 : 0; 70 | } 71 | catch (Exception ex) 72 | { 73 | Log.Error("AppSettings Error: Failed to convert usable data to save data", ex); 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Models/DayData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WorkLifeBalance.Models 4 | { 5 | [Serializable] 6 | public class DayData 7 | { 8 | public string Date { get; set; } = ""; 9 | public string WorkedAmmount { get; set; } = ""; 10 | public string RestedAmmount { get; set; } = ""; 11 | public string IdleAmmount { get; set; } = ""; 12 | 13 | public DateOnly DateC { get; set; } = DateOnly.FromDateTime(DateTime.Now); 14 | public TimeOnly WorkedAmmountC { get; set; } = new TimeOnly(0, 0, 0); 15 | public TimeOnly RestedAmmountC { get; set; } = new TimeOnly(0, 0, 0); 16 | public TimeOnly IdleAmmountC { get; set; } = new TimeOnly(0, 0, 0); 17 | 18 | public void ConvertSaveDataToUsableData() 19 | { 20 | try 21 | { 22 | if (string.IsNullOrEmpty(Date)) 23 | { 24 | return; 25 | } 26 | 27 | DateC = new DateOnly 28 | ( 29 | int.Parse(Date.Substring(4, 4)), 30 | int.Parse(Date.Substring(0, 2)), 31 | int.Parse(Date.Substring(2, 2)) 32 | ); 33 | 34 | WorkedAmmountC = new TimeOnly 35 | ( 36 | int.Parse(WorkedAmmount.Substring(0, 2)), 37 | int.Parse(WorkedAmmount.Substring(2, 2)), 38 | int.Parse(WorkedAmmount.Substring(4, 2)) 39 | ); 40 | 41 | RestedAmmountC = new TimeOnly 42 | ( 43 | int.Parse(RestedAmmount.Substring(0, 2)), 44 | int.Parse(RestedAmmount.Substring(2, 2)), 45 | int.Parse(RestedAmmount.Substring(4, 2)) 46 | ); 47 | 48 | IdleAmmountC = new TimeOnly 49 | ( 50 | int.Parse(IdleAmmount.Substring(0, 2)), 51 | int.Parse(IdleAmmount.Substring(2, 2)), 52 | int.Parse(IdleAmmount.Substring(4, 2)) 53 | ); 54 | } 55 | catch (Exception ex) 56 | { 57 | //MainWindow.ShowErrorBox("DayData Error", "Failed to convert data to usable data", ex); 58 | } 59 | } 60 | public void ConvertUsableDataToSaveData() 61 | { 62 | try 63 | { 64 | Date = DateC.ToString("MMddyyyy"); 65 | 66 | WorkedAmmount = WorkedAmmountC.ToString("HHmmss"); 67 | 68 | RestedAmmount = RestedAmmountC.ToString("HHmmss"); 69 | 70 | IdleAmmount = IdleAmmountC.ToString("HHmmss"); 71 | } 72 | catch (Exception ex) 73 | { 74 | //MainWindow.ShowErrorBox("DayData Error", "Failed to convert usable data to save data", ex); 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WorkLifeBalance 2 | 3 | WorkLifeBalance is a productivity application designed to help users monitor and optimize their time usage. The app provides automatic toggling between work and rest modes, detailed activity tracking, and a comparison of productivity metrics over time. 4 | 5 | ![WorkLifeBalance Overview](Assets/WorkLifeBalanceThumb.png) 6 | 7 | ## Features 8 | 9 | ### Time Tracking 10 | - **Automatic Toggles**: 11 | - Automatically detects the active window to determine if the user is working or resting. 12 | - Customize which applications are classified as "work" to ensure accurate tracking. 13 | 14 | ### Productivity Analysis 15 | - **Monthly Comparison**: 16 | - Compare current month's productivity metrics with last month's performance. 17 | - View detailed daily activity logs to understand time usage. 18 | - **Pomodoro Integration**: 19 | - Use the Pomodoro technique with a built-in "force work" option to eliminate distractions. 20 | - **Afk Detection** 21 | - Use mouse tracking to detect away from keyboard scenarios and switch to IDLE state 22 | - **Customizable** 23 | - Modify action intervals, save&load, state detection, window detect, afk detection and more 24 | 25 | ### Modular Architecture 26 | - Enable or disable features at runtime to suit your workflow and preferences. 27 | 28 | ### System Requirements 29 | - Requires Administrator privileges to monitor and track applications running with elevated permissions. 30 | 31 | ## Installation and Setup 32 | 33 | 1. Download the application from the official website and follow the instructions. 34 | https://roberbot.itch.io/work-life-balance 35 | 3. Launch the application with Administrator privileges to enable full functionality. 36 | 37 | ## Usage 38 | 39 | 1. Customize your settings: 40 | - Define which applications are considered "work." 41 | - Configure the Pomodoro timer for forced focus sessions when used. 42 | 2. Let the app track your activity automatically: 43 | - Monitor your productivity without manual toggles. 44 | 3. Analyze your productivity: 45 | - Compare monthly metrics and review daily activity to identify patterns. 46 | 47 | Detailed video tutorial: 48 | https://www.youtube.com/watch?v=PVNq04e8AJo 49 | 50 | ## Support 51 | If you like the app and want to support it: 52 | https://buymeacoffee.com/roberbot 53 | 54 | ## Future Planned Features 55 | I am currently working on something else, but when I come back I plan to add: 56 | - The ability to create custom states like "Learing" "Gaming" on top of the default "Resting, Idle, Working" states. 57 | - An **Advanced Detection** mode that's able to more accurate detect activities even specific webpages. 58 | - A possible port from WPF to Avalonia to allow for Linux support. 59 | - Enhanced documentation for a smoother community contribution process. 60 | - OPTIONAL OneDrive / google drive implementation for cross device activities share 61 | 62 | ## License 63 | This project is licensed under the MIT License. See the LICENSE file for details. 64 | -------------------------------------------------------------------------------- /Services/UpdateCheckerService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using WorkLifeBalance.Interfaces; 8 | using Newtonsoft.Json; 9 | using WorkLifeBalance.Models; 10 | using System.Net.Http; 11 | using Serilog; 12 | using WorkLifeBalance.Services.Feature; 13 | using WorkLifeBalance.ViewModels; 14 | 15 | namespace WorkLifeBalance.Services 16 | { 17 | public class UpdateCheckerService : IUpdateCheckerService 18 | { 19 | private readonly ISecondWindowService secondWindowService; 20 | private readonly IConfiguration configuration; 21 | private readonly DataStorageFeature dataStorageFeature; 22 | 23 | private readonly string UpdateAdress = ""; 24 | public UpdateCheckerService(ISecondWindowService secondWindowService, IConfiguration configuration, DataStorageFeature dataStorageFeature) 25 | { 26 | this.secondWindowService = secondWindowService; 27 | this.dataStorageFeature = dataStorageFeature; 28 | this.configuration = configuration; 29 | 30 | UpdateAdress = configuration.GetValue("UpdateDataAdress")!; 31 | } 32 | 33 | public async Task CheckForUpdate() 34 | { 35 | if (string.IsNullOrEmpty(UpdateAdress)) 36 | { 37 | Log.Error("UpdateDataAdress is empty inside the appsettings.json"); 38 | return; 39 | } 40 | 41 | VersionData? vdata = await DownloadLatestVersionData(); 42 | 43 | if(vdata == null) 44 | { 45 | Log.Error("Retrieved VersionData is null, problems with fetching update data"); 46 | return; 47 | } 48 | 49 | if(vdata.Version != dataStorageFeature.Settings.Version) 50 | { 51 | Log.Warning($"New Update Available! Current Version: {dataStorageFeature.Settings.Version}, Latest Version: {vdata.Version}"); 52 | await secondWindowService.OpenWindowWith(vdata); 53 | return; 54 | } 55 | 56 | Log.Information($"App is up to date! Current Version: {dataStorageFeature.Settings.Version}, Latest Version: {vdata.Version}"); 57 | } 58 | 59 | private async Task DownloadLatestVersionData() 60 | { 61 | using (HttpClient client = new HttpClient()) 62 | { 63 | try 64 | { 65 | string responseContent = await client.GetStringAsync(UpdateAdress); 66 | 67 | VersionData? gistData = JsonConvert.DeserializeObject(responseContent); 68 | return gistData; 69 | } 70 | catch (Exception ex) 71 | { 72 | Log.Error($"Error fetching Latest Version data: {ex.Message}"); 73 | return null; 74 | } 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Views/ForceStateMainMenuDetailsPage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 | 14 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Services/Feature/StateCheckerFeature.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace WorkLifeBalance.Services.Feature 7 | { 8 | public class StateCheckerFeature : FeatureBase 9 | { 10 | public bool IsFocusingOnWorkingWindow { get; set; } 11 | private readonly DataStorageFeature dataStorageFeature; 12 | private readonly ActivityTrackerFeature activityTrackerFeature; 13 | private readonly AppStateHandler appStateHandler; 14 | public StateCheckerFeature(DataStorageFeature dataStorageFeature, ActivityTrackerFeature activityTrackerFeature, AppStateHandler appStateHandler) 15 | { 16 | this.dataStorageFeature = dataStorageFeature; 17 | this.activityTrackerFeature = activityTrackerFeature; 18 | this.appStateHandler = appStateHandler; 19 | } 20 | 21 | protected override Func ReturnFeatureMethod() 22 | { 23 | return TriggerWorkDetect; 24 | } 25 | 26 | private async Task TriggerWorkDetect() 27 | { 28 | if (IsFeatureRuning) return; 29 | 30 | try 31 | { 32 | IsFeatureRuning = true; 33 | await Task.Delay(dataStorageFeature.Settings.AutoDetectInterval * 1000, CancelTokenS.Token); 34 | CheckStateChange(); 35 | } 36 | catch (TaskCanceledException taskCancel) 37 | { 38 | Log.Information($"State Checker: {taskCancel.Message}"); 39 | } 40 | catch (Exception ex) 41 | { 42 | Log.Error(ex, "State Checker"); 43 | } 44 | finally 45 | { 46 | IsFeatureRuning = false; 47 | } 48 | } 49 | 50 | private void CheckStateChange() 51 | { 52 | if (string.IsNullOrEmpty(activityTrackerFeature.ActiveWindow)) return; 53 | 54 | IsFocusingOnWorkingWindow = dataStorageFeature.AutoChangeData.WorkingStateWindows.Contains(activityTrackerFeature.ActiveWindow); 55 | 56 | switch (appStateHandler.AppTimerState) 57 | { 58 | case AppState.Working: 59 | if (!IsFocusingOnWorkingWindow) 60 | { 61 | appStateHandler.SetAppState(AppState.Resting); 62 | } 63 | break; 64 | 65 | case AppState.Resting: 66 | if (IsFocusingOnWorkingWindow) 67 | { 68 | appStateHandler.SetAppState(AppState.Working); 69 | } 70 | break; 71 | case AppState.Idle: 72 | if (IsFocusingOnWorkingWindow) 73 | { 74 | appStateHandler.SetAppState(AppState.Working); 75 | } 76 | else 77 | { 78 | appStateHandler.SetAppState(AppState.Resting); 79 | } 80 | break; 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Services/Feature/DataStorageFeature.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.Threading.Tasks; 4 | using WorkLifeBalance.Models; 5 | 6 | namespace WorkLifeBalance.Services.Feature 7 | { 8 | public class DataStorageFeature : FeatureBase 9 | { 10 | public bool IsAppSaving { get; private set; } 11 | public bool IsAppLoading { get; private set; } 12 | 13 | public bool IsClosingApp { get; set; } 14 | public bool IsAppReady { get; set; } 15 | 16 | public DayData TodayData { get; set; } = new(); 17 | public AppSettingsData Settings { get; set; } = new(); 18 | public AutoStateChangeData AutoChangeData { get; set; } = new(); 19 | 20 | public event Action? OnLoading; 21 | public event Action? OnLoaded; 22 | public event Action? OnSaving; 23 | public event Action? OnSaved; 24 | private readonly DataBaseHandler dataBaseHandler; 25 | public DataStorageFeature(DataBaseHandler dataBaseHandler) 26 | { 27 | this.dataBaseHandler = dataBaseHandler; 28 | } 29 | public async Task SaveData() 30 | { 31 | if (IsAppSaving) return; 32 | 33 | Log.Information($"Saving..."); 34 | 35 | IsAppSaving = true; 36 | 37 | OnSaving?.Invoke(); 38 | 39 | await dataBaseHandler.WriteDay(TodayData); 40 | await dataBaseHandler.WriteSettings(Settings); 41 | await dataBaseHandler.WriteAutoSateData(AutoChangeData); 42 | 43 | OnSaved?.Invoke(); 44 | 45 | IsAppSaving = false; 46 | 47 | Log.Information($"Save Complete!"); 48 | } 49 | 50 | public async Task LoadData() 51 | { 52 | if (IsAppLoading) return; 53 | 54 | IsAppLoading = true; 55 | 56 | OnLoading?.Invoke(); 57 | 58 | Log.Information($"Loading Day"); 59 | TodayData = await dataBaseHandler.ReadDay(TodayData.DateC.ToString("MMddyyyy")); 60 | Log.Information($"Loading Settings"); 61 | Settings = await dataBaseHandler.ReadSettings(); 62 | Log.Information($"Loading Activities"); 63 | AutoChangeData = await dataBaseHandler.ReadAutoStateData(TodayData.DateC.ToString("MMddyyyy")); 64 | 65 | OnLoaded?.Invoke(); 66 | 67 | IsAppLoading = false; 68 | Log.Information($"Load Complete!"); 69 | } 70 | 71 | protected override Func ReturnFeatureMethod() 72 | { 73 | return TriggerSaveData; 74 | } 75 | 76 | private async Task TriggerSaveData() 77 | { 78 | if (IsFeatureRuning) return; 79 | 80 | IsFeatureRuning = true; 81 | 82 | try 83 | { 84 | await Task.Delay(Settings.SaveInterval * 60000, CancelTokenS.Token); 85 | await SaveData(); 86 | } 87 | catch (TaskCanceledException taskCancel) 88 | { 89 | Log.Information($"DataStorage: {taskCancel.Message}"); 90 | } 91 | catch (Exception ex) 92 | { 93 | Log.Error(ex, "DataStorage"); 94 | } 95 | 96 | finally 97 | { 98 | IsFeatureRuning = false; 99 | } 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /ViewModels/BackgroundProcessesViewPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System.Collections.Generic; 4 | using System.Collections.ObjectModel; 5 | using System.Linq; 6 | using System.Numerics; 7 | using System.Threading.Tasks; 8 | using System.Windows.Controls; 9 | using WorkLifeBalance.Interfaces; 10 | using WorkLifeBalance.Services; 11 | using WorkLifeBalance.Services.Feature; 12 | 13 | namespace WorkLifeBalance.ViewModels 14 | { 15 | public partial class BackgroundProcessesViewPageVM : SecondWindowPageVMBase 16 | { 17 | public ObservableCollection DetectedWindows { get; set; } = new(); 18 | public ObservableCollection SelectedWindows { get; set; } = new(); 19 | 20 | [ObservableProperty] 21 | private string activeWindow = ""; 22 | 23 | private DataStorageFeature dataStorageFeature; 24 | private LowLevelHandler lowLevelHandler; 25 | private ActivityTrackerFeature activityTrackerFeature; 26 | private ISecondWindowService secondWindowService; 27 | public BackgroundProcessesViewPageVM(DataStorageFeature dataStorageFeature, LowLevelHandler lowLevelHandler, ActivityTrackerFeature activityTrackerFeature, ISecondWindowService secondWindowService) 28 | { 29 | PageHeight = 570; 30 | PageWidth = 700; 31 | PageName = "Customize Work Apps"; 32 | this.dataStorageFeature = dataStorageFeature; 33 | this.lowLevelHandler = lowLevelHandler; 34 | this.activityTrackerFeature = activityTrackerFeature; 35 | this.secondWindowService = secondWindowService; 36 | } 37 | 38 | private void UpdateActiveWindowUi(string newwindow) 39 | { 40 | ActiveWindow = newwindow; 41 | } 42 | 43 | private void InitializeProcessNames() 44 | { 45 | SelectedWindows = new ObservableCollection(dataStorageFeature.AutoChangeData.WorkingStateWindows); 46 | List allProcesses = lowLevelHandler.GetBackgroundApplicationsName(); 47 | DetectedWindows = new ObservableCollection(allProcesses.Except(SelectedWindows)); 48 | } 49 | 50 | public override Task OnPageOppeningAsync(object? args = null) 51 | { 52 | activityTrackerFeature.OnWindowChange += UpdateActiveWindowUi; 53 | InitializeProcessNames(); 54 | return Task.CompletedTask; 55 | } 56 | 57 | public override async Task OnPageClosingAsync() 58 | { 59 | activityTrackerFeature.OnWindowChange -= UpdateActiveWindowUi; 60 | dataStorageFeature.AutoChangeData.WorkingStateWindows = SelectedWindows.ToArray(); 61 | await dataStorageFeature.SaveData(); 62 | } 63 | 64 | [RelayCommand] 65 | private void ReturnToPreviousPage() 66 | { 67 | secondWindowService.OpenWindowWith(); 68 | } 69 | 70 | [RelayCommand] 71 | private void SelectProcess(string processName) 72 | { 73 | DetectedWindows.Remove(processName); 74 | SelectedWindows.Add(processName); 75 | } 76 | 77 | [RelayCommand] 78 | private void DeselectProcess(string processName) 79 | { 80 | SelectedWindows.Remove(processName); 81 | DetectedWindows.Add(processName); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Services/Feature/IdleCheckerFeature.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.IO.Pipes; 4 | using System.Numerics; 5 | using System.Threading.Tasks; 6 | using WorkLifeBalance.Interfaces; 7 | using static Dapper.SqlMapper; 8 | 9 | namespace WorkLifeBalance.Services.Feature 10 | { 11 | public class IdleCheckerFeature : FeatureBase 12 | { 13 | private Vector2 _oldmousePosition = new(-1, -1); 14 | private readonly AppStateHandler appStateHandler; 15 | private readonly DataStorageFeature dataStorageFeature; 16 | private readonly LowLevelHandler lowLevelHandler; 17 | private readonly IFeaturesServices featuresServices; 18 | 19 | private readonly int MinuteMiliseconds = 60000; 20 | private readonly int IdleDelay = 3000; 21 | private readonly int RestingDelay = 600000; 22 | public IdleCheckerFeature(DataStorageFeature dataStorageFeature, LowLevelHandler lowLevelHandler, AppStateHandler appStateHandler, IFeaturesServices featuresServices) 23 | { 24 | this.dataStorageFeature = dataStorageFeature; 25 | this.lowLevelHandler = lowLevelHandler; 26 | this.appStateHandler = appStateHandler; 27 | this.featuresServices = featuresServices; 28 | } 29 | 30 | protected override Func ReturnFeatureMethod() 31 | { 32 | return TriggerCheckIdle; 33 | } 34 | 35 | private async Task TriggerCheckIdle() 36 | { 37 | if (IsFeatureRuning) return; 38 | 39 | try 40 | { 41 | IsFeatureRuning = true; 42 | int delay; 43 | 44 | if (appStateHandler.AppTimerState == AppState.Idle) 45 | { 46 | delay = 2000; 47 | } 48 | else 49 | { 50 | delay = (dataStorageFeature.Settings.AutoDetectIdleInterval * 60000) / 2; 51 | } 52 | 53 | await Task.Delay(delay, CancelTokenS.Token); 54 | CheckIdle(); 55 | } 56 | catch (TaskCanceledException taskCancel) 57 | { 58 | Log.Information($"Idle Checker: {taskCancel.Message}"); 59 | } 60 | catch(Exception ex) 61 | { 62 | Log.Error(ex,"Idle Checker"); 63 | } 64 | finally 65 | { 66 | IsFeatureRuning = false; 67 | } 68 | } 69 | 70 | private void CheckIdle() 71 | { 72 | Vector2 newpos = Vector2.Zero; 73 | 74 | try 75 | { 76 | newpos = lowLevelHandler.GetMousePos(); 77 | } 78 | catch (Exception ex) 79 | { 80 | Log.Error(ex.Message); 81 | } 82 | 83 | if (_oldmousePosition == new Vector2(-1, -1)) 84 | { 85 | _oldmousePosition = newpos; 86 | return; 87 | } 88 | 89 | if (newpos == _oldmousePosition) 90 | { 91 | featuresServices.RemoveFeature(); 92 | appStateHandler.SetAppState(AppState.Idle); 93 | } 94 | else 95 | { 96 | featuresServices.AddFeature(); 97 | } 98 | 99 | _oldmousePosition = newpos; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Services/AppTimer.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using System; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using WorkLifeBalance.Interfaces; 7 | using WorkLifeBalance.Services.Feature; 8 | 9 | namespace WorkLifeBalance.Services 10 | { 11 | //Main timer that runs once a second, other features can subscribe to it and have their own run interval 12 | public class AppTimer 13 | { 14 | private readonly DataStorageFeature dataStorageFeature; 15 | private event Func? OnTimerTick; 16 | private CancellationTokenSource CancelTick = new(); 17 | 18 | public AppTimer(DataStorageFeature dataStorageFeature) 19 | { 20 | this.dataStorageFeature = dataStorageFeature; 21 | } 22 | 23 | public void StartTick() 24 | { 25 | CancelTick.Cancel(); 26 | 27 | CancelTick = new(); 28 | 29 | _ = TimerLoop(CancelTick.Token); 30 | } 31 | 32 | public bool IsFeaturePresent(Func eventname) 33 | { 34 | if (OnTimerTick != null) 35 | { 36 | return OnTimerTick.GetInvocationList().Contains(eventname); 37 | } 38 | return false; 39 | } 40 | 41 | public void Subscribe(Func eventname) 42 | { 43 | if (OnTimerTick != null) 44 | { 45 | if (OnTimerTick.GetInvocationList().Contains(eventname)) return; 46 | } 47 | OnTimerTick += eventname; 48 | Log.Information($"{eventname.Method.Name} Subscribed to Main Timer"); 49 | } 50 | 51 | public void UnSubscribe(Func eventname) 52 | { 53 | if (OnTimerTick == null) return; 54 | 55 | if (OnTimerTick.GetInvocationList().Contains(eventname)) 56 | { 57 | OnTimerTick -= eventname; 58 | Log.Information($"{eventname.Method.Name} UnSubscribed from Main Timer"); 59 | } 60 | } 61 | 62 | public void Stop() 63 | { 64 | CancelTick.Cancel(); 65 | } 66 | 67 | private async Task TimerLoop(CancellationToken token) 68 | { 69 | while (!token.IsCancellationRequested) 70 | { 71 | //stop the timer if the app is not ready or is closing 72 | if (!dataStorageFeature.IsAppReady && dataStorageFeature.IsClosingApp) 73 | { 74 | Stop(); 75 | return; 76 | } 77 | 78 | try 79 | { 80 | //Delay the triggering of the main event to pause every feature from being 81 | //triggered while saving, so data is not updated while is saving 82 | if (dataStorageFeature.IsAppSaving) 83 | { 84 | await Task.Delay(500, token); 85 | continue; 86 | } 87 | 88 | await Task.Delay(1000, token); 89 | } 90 | catch (TaskCanceledException taskCancel) 91 | { 92 | Log.Information($"App Timer: {taskCancel.Message}"); 93 | } 94 | catch (Exception ex) 95 | { 96 | Log.Error(ex, "App Timer"); 97 | } 98 | 99 | OnTimerTick?.Invoke(); 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 54 | 62 | 63 | 64 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /ViewModels/SettingsPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using IWshRuntimeLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using WorkLifeBalance.Interfaces; 7 | using WorkLifeBalance.Services; 8 | using WorkLifeBalance.Services.Feature; 9 | using File = System.IO.File; 10 | using Path = System.IO.Path; 11 | 12 | namespace WorkLifeBalance.ViewModels 13 | { 14 | public partial class SettingsPageVM : SecondWindowPageVMBase 15 | { 16 | [ObservableProperty] 17 | private string version = ""; 18 | 19 | [ObservableProperty] 20 | private int autoSaveInterval = 5; 21 | 22 | [ObservableProperty] 23 | private int autoDetectInterval = 1; 24 | 25 | [ObservableProperty] 26 | private int autoDetectIdleInterval = 1; 27 | 28 | [ObservableProperty] 29 | private bool startWithWin = false; 30 | 31 | [ObservableProperty] 32 | private bool minimizeToTray = false; 33 | 34 | [ObservableProperty] 35 | private int[]? numbers; 36 | 37 | private readonly DataStorageFeature dataStorageFeature; 38 | private readonly IFeaturesServices featuresServices; 39 | private readonly LowLevelHandler lowLevelHandler; 40 | public SettingsPageVM(DataStorageFeature dataStorageFeature, IFeaturesServices featuresServices, LowLevelHandler lowLevelHandler) 41 | { 42 | this.featuresServices = featuresServices; 43 | this.dataStorageFeature = dataStorageFeature; 44 | this.lowLevelHandler = lowLevelHandler; 45 | PageHeight = 320; 46 | PageWidth = 250; 47 | PageName = "Settings"; 48 | 49 | InitializeData(); 50 | } 51 | 52 | private void InitializeData() 53 | { 54 | Version = $"Version: {dataStorageFeature.Settings.Version}"; 55 | 56 | AutoSaveInterval = dataStorageFeature.Settings.SaveInterval; 57 | 58 | AutoDetectInterval = dataStorageFeature.Settings.AutoDetectInterval; 59 | 60 | AutoDetectIdleInterval = dataStorageFeature.Settings.AutoDetectIdleInterval; 61 | 62 | StartWithWin = dataStorageFeature.Settings.StartWithWindowsC; 63 | 64 | MinimizeToTray = dataStorageFeature.Settings.MinimizeToTrayC; 65 | 66 | List numbersTemp = new(); 67 | for(int x = 1; x <= 300; x++) 68 | { 69 | numbersTemp.Add(x); 70 | } 71 | Numbers = numbersTemp.ToArray(); 72 | } 73 | 74 | public override async Task OnPageClosingAsync() 75 | { 76 | dataStorageFeature.Settings.SaveInterval = AutoSaveInterval; 77 | 78 | dataStorageFeature.Settings.AutoDetectInterval = AutoDetectInterval; 79 | 80 | dataStorageFeature.Settings.AutoDetectIdleInterval = AutoDetectIdleInterval; 81 | 82 | dataStorageFeature.Settings.StartWithWindowsC = StartWithWin; 83 | 84 | dataStorageFeature.Settings.MinimizeToTrayC = MinimizeToTray; 85 | 86 | await dataStorageFeature.SaveData(); 87 | 88 | ApplyStartToWindows(); 89 | dataStorageFeature.Settings.OnSettingsChanged.Invoke(); 90 | } 91 | 92 | private void ApplyStartToWindows() 93 | { 94 | if (dataStorageFeature.Settings.StartWithWindowsC) 95 | { 96 | lowLevelHandler.CreateStartupShortcut(); 97 | } 98 | else 99 | { 100 | lowLevelHandler.DeleteStartupShortcut(); 101 | } 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /SecondWindow.xaml: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 48 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Views/ForceWorkMainMenuDetailsPage.xaml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 35 | 36 | 37 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 49 | 50 | 51 | 52 | 53 | 54 | 56 | 57 | 59 | 60 | 61 | 62 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /ViewModels/MainMenuVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using Serilog; 4 | using System; 5 | using System.Net; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | using WorkLifeBalance.Interfaces; 9 | using WorkLifeBalance.Services; 10 | using WorkLifeBalance.Services.Feature; 11 | 12 | namespace WorkLifeBalance.ViewModels 13 | { 14 | public partial class MainWindowVM : ObservableObject 15 | { 16 | [ObservableProperty] 17 | private string? dateText; 18 | 19 | [ObservableProperty] 20 | private TimeOnly elapsedWorkTime; 21 | 22 | [ObservableProperty] 23 | private TimeOnly elapsedRestTime; 24 | 25 | [ObservableProperty] 26 | private TimeOnly elapsedIdleTime; 27 | 28 | [ObservableProperty] 29 | private AppState appState = AppState.Resting; 30 | 31 | public bool MinimizeToTray 32 | { 33 | get 34 | { 35 | return dataStorageFeature.Settings.MinimizeToTrayC; 36 | } 37 | } 38 | 39 | public IMainWindowDetailsService MainWindowDetailsService { get; set; } 40 | 41 | private readonly AppStateHandler appStateHandler; 42 | private readonly LowLevelHandler lowLevelHandler; 43 | private readonly DataStorageFeature dataStorageFeature; 44 | private readonly TimeTrackerFeature timeTrackerFeature; 45 | private readonly IFeaturesServices featuresServices; 46 | private readonly ISecondWindowService secondWindowService; 47 | 48 | public MainWindowVM(AppTimer mainTimer, LowLevelHandler lowLevelHandler, DataStorageFeature dataStorageFeature, TimeTrackerFeature timeTrackerFeature, ISecondWindowService secondWindowService, AppStateHandler appStateHandler, IMainWindowDetailsService mainWindowDetailsService, IFeaturesServices featuresServices) 49 | { 50 | this.lowLevelHandler = lowLevelHandler; 51 | this.dataStorageFeature = dataStorageFeature; 52 | this.timeTrackerFeature = timeTrackerFeature; 53 | this.secondWindowService = secondWindowService; 54 | this.appStateHandler = appStateHandler; 55 | this.MainWindowDetailsService = mainWindowDetailsService; 56 | this.featuresServices = featuresServices; 57 | 58 | DateText = $"Today: {dataStorageFeature.TodayData.DateC:MM/dd/yyyy}"; 59 | 60 | SubscribeToEvents(); 61 | } 62 | 63 | private void SubscribeToEvents() 64 | { 65 | appStateHandler.OnStateChanges += OnStateChanged; 66 | 67 | dataStorageFeature.OnSaving += OnSavingData; 68 | dataStorageFeature.OnSaved += OnDataSaved; 69 | 70 | timeTrackerFeature.OnSpentTimeChange += OnTimeSpentChanged; 71 | } 72 | 73 | private void OnStateChanged(AppState state) 74 | { 75 | AppState = state; 76 | } 77 | 78 | private void OnSavingData() 79 | { 80 | DateText = "Saving data..."; 81 | } 82 | 83 | private void OnDataSaved() 84 | { 85 | DateText = $"Today: {dataStorageFeature.TodayData.DateC:MM/dd/yyyy}"; 86 | } 87 | 88 | private void OnTimeSpentChanged() 89 | { 90 | ElapsedWorkTime = dataStorageFeature.TodayData.WorkedAmmountC; 91 | ElapsedRestTime = dataStorageFeature.TodayData.RestedAmmountC; 92 | ElapsedIdleTime = dataStorageFeature.TodayData.IdleAmmountC; 93 | } 94 | 95 | [RelayCommand] 96 | private void ToggleForceState() 97 | { 98 | if (featuresServices.IsFeaturePresent()) 99 | { 100 | featuresServices.RemoveFeature(); 101 | } 102 | else 103 | { 104 | featuresServices.AddFeature(); 105 | } 106 | } 107 | 108 | [RelayCommand] 109 | private void OpenViewDataWindow() 110 | { 111 | secondWindowService.OpenWindowWith(); 112 | } 113 | 114 | [RelayCommand] 115 | private void OpenOptionsWindow() 116 | { 117 | secondWindowService.OpenWindowWith(); 118 | } 119 | 120 | [RelayCommand] 121 | private void CloseApp() 122 | { 123 | secondWindowService.OpenWindowWith(); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /Services/SqlDataAccess.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using System.Data.SQLite; 4 | using System.Threading; 5 | using System.Linq; 6 | using Serilog; 7 | using System; 8 | using Dapper; 9 | using Microsoft.Extensions.Configuration; 10 | 11 | namespace WorkLifeBalance.Services 12 | { 13 | public class SqlDataAccess 14 | { 15 | private readonly IConfiguration configuration; 16 | private readonly SemaphoreSlim _semaphore = new(1); 17 | //use config to read the connection string 18 | private string ConnectionString = ""; 19 | 20 | public SqlDataAccess(IConfiguration configuration) 21 | { 22 | this.configuration = configuration; 23 | 24 | string? overridedDirectory = configuration.GetValue("OverrideDbDirectory"); 25 | 26 | if (string.IsNullOrEmpty(overridedDirectory)) 27 | { 28 | ConnectionString = @$"Data Source={Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\WorkLifeBalance\RecordedData.db;Version=3;"; 29 | } 30 | else 31 | { 32 | ConnectionString = @$"Data Source={overridedDirectory}\RecordedData.db;Version=3;"; 33 | } 34 | } 35 | 36 | public async Task ExecuteAsync(string sql, T parameters) 37 | { 38 | await _semaphore.WaitAsync(); 39 | try 40 | { 41 | using (SQLiteConnection connection = new(ConnectionString)) 42 | { 43 | await connection.OpenAsync(); 44 | 45 | using (SQLiteTransaction transaction = connection.BeginTransaction()) 46 | { 47 | try 48 | { 49 | var rows = await connection.ExecuteScalarAsync(sql, parameters); 50 | await transaction.CommitAsync(); 51 | return rows; 52 | } 53 | catch (Exception ex) 54 | { 55 | Log.Error($"Execute SQL error with sql: {sql} Error: {ex}"); 56 | await transaction.RollbackAsync(); 57 | throw; 58 | } 59 | } 60 | } 61 | } 62 | finally 63 | { 64 | _semaphore.Release(); 65 | } 66 | } 67 | 68 | public async Task WriteDataAsync(string sql, T parameters) 69 | { 70 | await _semaphore.WaitAsync(); 71 | try 72 | { 73 | using (SQLiteConnection connection = new(ConnectionString)) 74 | { 75 | await connection.OpenAsync(); 76 | 77 | using (SQLiteTransaction transaction = connection.BeginTransaction()) 78 | { 79 | try 80 | { 81 | var rows = await connection.ExecuteAsync(sql, parameters); 82 | await transaction.CommitAsync(); 83 | 84 | return rows; 85 | } 86 | catch (Exception ex) 87 | { 88 | Log.Error($"Write data to database error with sql {sql}, parameters {parameters}: Error {ex}"); 89 | await transaction.RollbackAsync(); 90 | throw; 91 | } 92 | } 93 | } 94 | } 95 | finally 96 | { 97 | _semaphore.Release(); 98 | } 99 | } 100 | 101 | public async Task> ReadDataAsync(string sql, U parameters) 102 | { 103 | await _semaphore.WaitAsync(); 104 | try 105 | { 106 | using (SQLiteConnection connection = new(ConnectionString)) 107 | { 108 | await connection.OpenAsync(); 109 | try 110 | { 111 | var rows = await connection.QueryAsync(sql, parameters); 112 | return rows.ToList(); 113 | } 114 | catch (Exception ex) 115 | { 116 | Log.Error($"Read data from database error with sql {sql}, parameters {parameters}: Error {ex}"); 117 | throw; 118 | } 119 | } 120 | } 121 | finally 122 | { 123 | _semaphore.Release(); 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /ViewModels/ForceWorkPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Collections.ObjectModel; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using WorkLifeBalance.Interfaces; 10 | using WorkLifeBalance.Services.Feature; 11 | 12 | namespace WorkLifeBalance.ViewModels 13 | { 14 | public partial class ForceWorkPageVM : SecondWindowPageVMBase 15 | { 16 | [ObservableProperty] 17 | private int[] hours = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; 18 | 19 | [ObservableProperty] 20 | private int[] minutes = {0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55}; 21 | 22 | [ObservableProperty] 23 | private int totalWorkHours = 2; 24 | 25 | [ObservableProperty] 26 | private int totalWorkMinutes; 27 | 28 | [ObservableProperty] 29 | private int workHours; 30 | 31 | [ObservableProperty] 32 | private int workMinutes = 25; 33 | 34 | [ObservableProperty] 35 | private int restHours; 36 | 37 | [ObservableProperty] 38 | private int restMinutes = 5; 39 | 40 | [ObservableProperty] 41 | private int longRestHours; 42 | 43 | [ObservableProperty] 44 | private int longRestMinutes = 25; 45 | 46 | [ObservableProperty] 47 | private int longRestInterval = 4; 48 | 49 | [ObservableProperty] 50 | private bool isFeatureActiv; 51 | 52 | [ObservableProperty] 53 | private int maxWarnings = 3; 54 | 55 | [ObservableProperty] 56 | private TimeOnly totalWorkTimeSetting; 57 | [ObservableProperty] 58 | private TimeOnly workTimeSetting; 59 | [ObservableProperty] 60 | private TimeOnly restTimeSetting; 61 | [ObservableProperty] 62 | private TimeOnly longRestTimeSetting; 63 | [ObservableProperty] 64 | private int longRestIntervalSetting; 65 | 66 | [ObservableProperty] 67 | private int distractionCount; 68 | 69 | [ObservableProperty] 70 | private string[] distractions = { "Process.exe", "Process.exe", "Process.exe" }; 71 | 72 | private readonly ForceWorkFeature forceWorkFeature; 73 | private readonly ISecondWindowService secondWindowService; 74 | private readonly IFeaturesServices featuresServices; 75 | 76 | public ForceWorkPageVM(ForceWorkFeature forceWorkFeature, ISecondWindowService secondWindowService, IFeaturesServices featuresServices) 77 | { 78 | this.forceWorkFeature = forceWorkFeature; 79 | this.featuresServices = featuresServices; 80 | this.secondWindowService = secondWindowService; 81 | PageHeight = 410; 82 | PageWidth = 400; 83 | PageName = "Force Work"; 84 | } 85 | 86 | //maybe use observable pattern for properties instead of one onUpdate event 87 | private void UpdateDataFromForceWork() 88 | { 89 | Distractions = forceWorkFeature.Distractions; 90 | DistractionCount = forceWorkFeature.DistractionsCount; 91 | IsFeatureActiv = featuresServices.IsFeaturePresent(); 92 | } 93 | 94 | private void GetForceWorkSettings() 95 | { 96 | TotalWorkTimeSetting = forceWorkFeature.TotalWorkTimeSetting; 97 | WorkTimeSetting = forceWorkFeature.WorkTimeSetting; 98 | RestTimeSetting = forceWorkFeature.RestTimeSetting; 99 | LongRestTimeSetting = forceWorkFeature.LongRestTimeSetting; 100 | LongRestIntervalSetting = forceWorkFeature.LongRestIntervalSetting; 101 | } 102 | 103 | public override Task OnPageOppeningAsync(object? args = null) 104 | { 105 | IsFeatureActiv = featuresServices.IsFeaturePresent(); 106 | forceWorkFeature.OnDataUpdated += UpdateDataFromForceWork; 107 | return Task.CompletedTask; 108 | } 109 | 110 | public override Task OnPageClosingAsync() 111 | { 112 | forceWorkFeature.OnDataUpdated -= UpdateDataFromForceWork; 113 | return Task.CompletedTask; 114 | } 115 | 116 | [RelayCommand] 117 | private void ReturnToOptions() 118 | { 119 | secondWindowService.OpenWindowWith(); 120 | } 121 | 122 | [RelayCommand] 123 | private void ToggleForceWork() 124 | { 125 | if (IsFeatureActiv) 126 | { 127 | featuresServices.RemoveFeature(); 128 | IsFeatureActiv = false; 129 | } 130 | else 131 | { 132 | forceWorkFeature.SetWorkTime(WorkHours, WorkMinutes, MaxWarnings); 133 | forceWorkFeature.SetRestTime(RestHours, RestMinutes); 134 | forceWorkFeature.SetTotalWorkTime(TotalWorkHours, TotalWorkMinutes); 135 | forceWorkFeature.SetLongRestTime(LongRestHours, LongRestMinutes, LongRestInterval); 136 | 137 | GetForceWorkSettings(); 138 | featuresServices.AddFeature(); 139 | IsFeatureActiv = true; 140 | } 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /Views/OptionsPage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 13 | 14 | 15 | 29 | 44 | 60 | 76 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /WorkLifeBalance.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | net8.0-windows7.0 6 | enable 7 | true 8 | true 9 | true 10 | Assets\WorkLifeBalanceLogo.ico 11 | app.manifest 12 | 13 | 6.0-recommended 14 | $(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | tlbimp 46 | 0 47 | 1 48 | f935dc20-1cf0-11d0-adb9-00c04fd58a0b 49 | 0 50 | false 51 | true 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | PreserveNewest 74 | 75 | 76 | PreserveNewest 77 | 78 | 79 | PreserveNewest 80 | 81 | 82 | PreserveNewest 83 | 84 | 85 | PreserveNewest 86 | 87 | 88 | PreserveNewest 89 | 90 | 91 | PreserveNewest 92 | 93 | 94 | PreserveNewest 95 | 96 | 97 | PreserveNewest 98 | 99 | 100 | PreserveNewest 101 | 102 | 103 | PreserveNewest 104 | 105 | 106 | PreserveNewest 107 | 108 | 109 | PreserveNewest 110 | 111 | 112 | PreserveNewest 113 | 114 | 115 | PreserveNewest 116 | 117 | 118 | 119 | 120 | 121 | Never 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /ViewModels/ViewDaysPageVM.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using WorkLifeBalance.Models; 6 | using WorkLifeBalance.Interfaces; 7 | using CommunityToolkit.Mvvm.Input; 8 | using WorkLifeBalance.Services; 9 | using CommunityToolkit.Mvvm.ComponentModel; 10 | using System; 11 | using WorkLifeBalance.Services.Feature; 12 | 13 | namespace WorkLifeBalance.ViewModels 14 | { 15 | public partial class ViewDaysPageVM : SecondWindowPageVMBase 16 | { 17 | public ObservableCollection LoadedData { get; set; } = new(); 18 | 19 | [ObservableProperty] 20 | private int[]? filterDays; 21 | 22 | [ObservableProperty] 23 | private int selectedDay = 0; 24 | 25 | [ObservableProperty] 26 | private int[]? filterMonths; 27 | 28 | [ObservableProperty] 29 | private int selectedMonth = 0; 30 | 31 | [ObservableProperty] 32 | private int[]? filterYears; 33 | 34 | [ObservableProperty] 35 | private int selectedYear = 0; 36 | 37 | private DayData[]? backupdata; 38 | //use this to request the correct page when leaving the DayActivity page 39 | private int LoadedPageType; 40 | private ISecondWindowService secondWindowService; 41 | private DataBaseHandler database; 42 | private DataStorageFeature dataStorage; 43 | public ViewDaysPageVM(ISecondWindowService secondWindowService, DataBaseHandler database, DataStorageFeature dataStorage) 44 | { 45 | PageHeight = 570; 46 | PageWidth = 710; 47 | this.secondWindowService = secondWindowService; 48 | this.database = database; 49 | this.dataStorage = dataStorage; 50 | SetFilterValues(); 51 | } 52 | 53 | private void SetFilterValues() 54 | { 55 | //use the database to choose what days/month/years should the filters contain 56 | DateOnly Today = dataStorage.TodayData.DateC; 57 | List Days = new(); 58 | List Months = new(); 59 | List Years = new(); 60 | for (int x = 0; x < 31; x++) 61 | { 62 | Days.Add(x); 63 | FilterDays = Days.ToArray(); 64 | } 65 | for (int x = 0; x < 13; x++) 66 | { 67 | Months.Add(x); 68 | FilterMonths = Months.ToArray(); 69 | } 70 | for (int x = Today.Year; x > 2020 ; x--) 71 | { 72 | Years.Add(x); 73 | } 74 | Years.Add(0); 75 | FilterYears = Years.ToArray(); 76 | } 77 | 78 | private async Task RequiestData(int requiestedDataType = 0) 79 | { 80 | DateOnly currentDate = dataStorage.TodayData.DateC; 81 | DateTime previousMonthDateTime = currentDate.ToDateTime(new TimeOnly(0, 0, 0)).AddMonths(-1); 82 | DateOnly previousDate = DateOnly.FromDateTime(previousMonthDateTime); 83 | 84 | List Days = new(); 85 | switch (requiestedDataType) 86 | { 87 | case 0: 88 | Days = await database.ReadMonth(); 89 | PageName = "All Months Days"; 90 | break; 91 | case 1: 92 | Days = await database.ReadMonth(currentDate.ToString("MM"), currentDate.ToString("yyyy")); 93 | PageName = "Current Month Days"; 94 | break; 95 | case 2: 96 | Days = await database.ReadMonth(previousDate.ToString("MM"), previousDate.ToString("yyyy")); 97 | PageName = "Previous Month Days"; 98 | break; 99 | } 100 | 101 | SelectedMonth = 0; 102 | SelectedDay = 0; 103 | SelectedYear = 0; 104 | 105 | Days.Reverse(); 106 | LoadedData = new ObservableCollection(Days); 107 | 108 | backupdata = LoadedData.ToArray(); 109 | } 110 | 111 | public override async Task OnPageOppeningAsync(object? args = null) 112 | { 113 | if (args != null) 114 | { 115 | if (args is int loadedpagetype) 116 | { 117 | await RequiestData(loadedpagetype); 118 | LoadedPageType = loadedpagetype; 119 | } 120 | } 121 | } 122 | 123 | [RelayCommand] 124 | private void ReturnToPreviousPage() 125 | { 126 | secondWindowService.OpenWindowWith(); 127 | } 128 | 129 | [RelayCommand] 130 | private void ViewDay(DayData data) 131 | { 132 | data.ConvertSaveDataToUsableData(); 133 | 134 | secondWindowService.OpenWindowWith((LoadedPageType, data)); 135 | } 136 | 137 | [RelayCommand] 138 | private void ApplyFilters() 139 | { 140 | if (SelectedMonth == 0 && SelectedDay == 0 && SelectedYear == 0) 141 | { 142 | LoadedData.Clear(); 143 | 144 | foreach (DayData day in backupdata!) 145 | { 146 | LoadedData.Add(day); 147 | } 148 | return; 149 | } 150 | 151 | DayData[] tempdata = backupdata!; 152 | if (SelectedMonth != 0) 153 | { 154 | tempdata = tempdata.Where(daydata => daydata.DateC.Month == SelectedMonth).ToArray(); 155 | } 156 | if (SelectedDay != 0) 157 | { 158 | tempdata = tempdata.Where(daydata => daydata.DateC.Day == SelectedDay).ToArray(); 159 | } 160 | if (SelectedYear != 0) 161 | { 162 | tempdata = tempdata.Where(daydata => daydata.DateC.Year == SelectedYear).ToArray(); 163 | } 164 | 165 | LoadedData.Clear(); 166 | 167 | foreach (DayData day in tempdata) 168 | { 169 | LoadedData.Add(day); 170 | } 171 | } 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Configuration; 3 | using WorkLifeBalance.Services.Feature; 4 | using WorkLifeBalance.Interfaces; 5 | using WorkLifeBalance.ViewModels; 6 | using WorkLifeBalance.Services; 7 | using System.Diagnostics; 8 | using System.Windows; 9 | using System.IO; 10 | using Serilog; 11 | using System; 12 | using System.Threading.Tasks; 13 | using WorkLifeBalance.ViewModels.Base; 14 | 15 | namespace WorkLifeBalance 16 | { 17 | /// 18 | /// Interaction logic for App.xaml 19 | /// 20 | public partial class App : Application 21 | { 22 | private readonly ServiceProvider _servicesProvider; 23 | private readonly IConfiguration _configuration; 24 | public App() 25 | { 26 | var builder = new ConfigurationBuilder() 27 | .SetBasePath(Directory.GetCurrentDirectory()) 28 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); 29 | 30 | _configuration = builder.Build(); 31 | 32 | IServiceCollection services = new ServiceCollection(); 33 | 34 | ConfigureServices(services); 35 | 36 | _servicesProvider = services.BuildServiceProvider(); 37 | } 38 | 39 | private void ConfigureServices(IServiceCollection services) 40 | { 41 | services.AddSingleton(); 42 | services.AddSingleton(); 43 | services.AddSingleton(); 44 | services.AddSingleton(); 45 | services.AddSingleton(); 46 | services.AddSingleton(); 47 | 48 | services.AddSingleton(); 49 | services.AddSingleton(); 50 | 51 | services.AddSingleton(); 52 | services.AddSingleton(); 53 | services.AddSingleton(); 54 | services.AddSingleton(); 55 | services.AddSingleton(); 56 | services.AddSingleton(); 57 | services.AddSingleton(); 58 | 59 | services.AddSingleton(); 60 | services.AddSingleton(_configuration); 61 | services.AddSingleton(); 62 | services.AddSingleton(); 63 | services.AddSingleton(); 64 | services.AddSingleton(); 65 | services.AddSingleton(); 66 | 67 | //factory method for ViewModelBase. 68 | services.AddSingleton>(serviceProvider => viewModelType => (ViewModelBase)serviceProvider.GetRequiredService(viewModelType)); 69 | //factory method for Features. 70 | services.AddSingleton>(serviceProvider => featureBase => (FeatureBase)serviceProvider.GetRequiredService(featureBase)); 71 | 72 | services.AddSingleton(); 73 | services.AddSingleton(); 74 | services.AddSingleton(); 75 | services.AddSingleton(); 76 | services.AddSingleton(); 77 | services.AddSingleton(); 78 | services.AddSingleton(); 79 | services.AddSingleton(); 80 | services.AddSingleton(); 81 | services.AddSingleton(); 82 | services.AddSingleton(); 83 | services.AddSingleton(); 84 | 85 | services.AddSingleton(); 86 | services.AddSingleton(); 87 | } 88 | 89 | protected override void OnStartup(StartupEventArgs e) 90 | { 91 | base.OnStartup(e); 92 | 93 | LowLevelHandler lowHandler = _servicesProvider.GetRequiredService(); 94 | 95 | bool isDebug = _configuration.GetValue("Debug"); 96 | if (isDebug) 97 | { 98 | lowHandler.EnableConsole(); 99 | Log.Logger = new LoggerConfiguration() 100 | .WriteTo.Console() 101 | .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day) 102 | .CreateLogger(); 103 | } 104 | else 105 | { 106 | Log.Logger = new LoggerConfiguration() 107 | .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day) 108 | .CreateLogger(); 109 | } 110 | _ = InitializeApp(); 111 | } 112 | 113 | private async Task InitializeApp() 114 | { 115 | //request the secondWindow so we will have it there to subscribe to events 116 | _servicesProvider.GetRequiredService(); 117 | 118 | DataStorageFeature dataStorageFeature = _servicesProvider.GetRequiredService(); 119 | 120 | SqlLiteDatabaseIntegrity sqlLiteDatabaseIntegrity = _servicesProvider.GetRequiredService(); 121 | 122 | IUpdateCheckerService updateCheckerService = _servicesProvider.GetRequiredService(); 123 | 124 | await updateCheckerService.CheckForUpdate(); 125 | 126 | await sqlLiteDatabaseIntegrity.CheckDatabaseIntegrity(); 127 | 128 | await dataStorageFeature.LoadData(); 129 | 130 | AppTimer appTimer = _servicesProvider.GetRequiredService(); 131 | 132 | //set app ready so timers can start 133 | dataStorageFeature.IsAppReady = true; 134 | 135 | IFeaturesServices featuresService = _servicesProvider.GetRequiredService(); 136 | featuresService.AddFeature(); 137 | featuresService.AddFeature(); 138 | featuresService.AddFeature(); 139 | featuresService.AddFeature(); 140 | featuresService.AddFeature(); 141 | 142 | //starts the main timer 143 | appTimer.StartTick(); 144 | 145 | _servicesProvider.GetRequiredService().Show(); 146 | 147 | Log.Information("------------------App Initialized------------------"); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /Views/ViewDayDetailsPage.xaml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 30 | 31 | 32 | 33 | 34 | 37 | 38 | 39 | 40 | 41 | 44 | 45 | 51 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 75 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 107 | 108 | 109 | 110 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /Views/SettingsPage.xaml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 27 | 28 | 32 | 33 | 34 | 35 | 40 | 45 | 46 | 47 | 48 | 49 | 53 | 54 | 55 | 56 | 61 | 66 | 67 | 68 | 69 | 70 | 75 | 76 | 77 | 78 | 83 | 90 | 91 | 92 | 96 | 97 | 102 | 109 | 110 | 111 | 115 | 116 | 121 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /Services/LowLevelHandler.cs: -------------------------------------------------------------------------------- 1 | using IWshRuntimeLibrary; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Numerics; 8 | using System.Runtime.InteropServices; 9 | using Microsoft.Win32.TaskScheduler; 10 | using System.Text; 11 | using WorkLifeBalance.Services.Feature; 12 | 13 | using File = System.IO.File; 14 | using Serilog; 15 | 16 | namespace WorkLifeBalance.Services 17 | { 18 | //low level handling of windows and mouse 19 | public class LowLevelHandler 20 | { 21 | private readonly DataStorageFeature dataStorageFeature; 22 | public LowLevelHandler(DataStorageFeature dataStorageFeature) 23 | { 24 | this.dataStorageFeature = dataStorageFeature; 25 | } 26 | 27 | [DllImport("user32.dll")] 28 | private static extern bool GetCursorPos(out POINT lpPoint); 29 | 30 | [DllImport("kernel32.dll")] 31 | private static extern bool AllocConsole(); 32 | 33 | [DllImport("user32.dll")] 34 | [return: MarshalAs(UnmanagedType.Bool)] 35 | private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, nint lParam); 36 | private delegate bool EnumWindowsProc(nint hWnd, nint lParam); 37 | 38 | [DllImport("user32.dll")] 39 | [return: MarshalAs(UnmanagedType.Bool)] 40 | private static extern bool IsWindowVisible(nint hWnd); 41 | 42 | [DllImport("user32.dll", SetLastError = true)] 43 | static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); 44 | const byte VK_LWIN = 0x5B; // Virtual Key for Left Windows key 45 | const byte VK_D = 0x44; // Virtual Key for 'D' key 46 | const uint KEYEVENTF_KEYUP = 0x0002; // Flag for key release 47 | 48 | [DllImport("user32.dll")] 49 | private static extern nint GetForegroundWindow(); 50 | 51 | [DllImport("user32.dll", SetLastError = true)] 52 | private static extern uint GetWindowThreadProcessId(nint hWnd, out uint lpdwProcessId); 53 | 54 | [DllImport("psapi.dll")] 55 | private static extern uint GetModuleFileNameEx(nint hProcess, nint hModule, StringBuilder lpBaseName, int nSize); 56 | 57 | //create a point to store thelocation of a point on the screen 58 | [StructLayout(LayoutKind.Sequential)] 59 | private struct POINT 60 | { 61 | public int X; 62 | public int Y; 63 | } 64 | 65 | public void EnableConsole() 66 | { 67 | AllocConsole(); 68 | } 69 | 70 | public void OpenLink(string link) 71 | { 72 | Process.Start(new ProcessStartInfo(link) { UseShellExecute = true }); 73 | } 74 | 75 | public void MinimizeAllApps() 76 | { 77 | // win down 78 | keybd_event(VK_LWIN, 0, 0, UIntPtr.Zero); 79 | // D down 80 | keybd_event(VK_D, 0, 0, UIntPtr.Zero); 81 | 82 | // d up 83 | keybd_event(VK_D, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); 84 | // win up 85 | keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); 86 | } 87 | 88 | public void CreateStartupShortcut() 89 | { 90 | try 91 | { 92 | using (TaskService taskService = new TaskService()) 93 | { 94 | DeleteStartupShortcut(); 95 | 96 | TaskDefinition taskDefinition = taskService.NewTask(); 97 | taskDefinition.RegistrationInfo.Description = $"Run {dataStorageFeature.Settings.AppName} at windows startup as administrator to start recording activity."; 98 | 99 | taskDefinition.Triggers.Add(new LogonTrigger()); 100 | 101 | taskDefinition.Actions.Add(new ExecAction(dataStorageFeature.Settings.AppExePath, null, dataStorageFeature.Settings.AppDirectory)); 102 | 103 | taskDefinition.Settings.StopIfGoingOnBatteries = false; 104 | taskDefinition.Settings.StartWhenAvailable = true; 105 | taskDefinition.Settings.RestartInterval = TimeSpan.FromMinutes(1); 106 | taskDefinition.Settings.RestartCount = 3; 107 | taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.Zero; 108 | 109 | taskDefinition.Principal.RunLevel = TaskRunLevel.Highest; 110 | taskService.RootFolder.RegisterTaskDefinition(dataStorageFeature.Settings.AppName, taskDefinition); 111 | } 112 | } 113 | catch(Exception ex) 114 | { 115 | Log.Error(ex.Message); 116 | Log.Error(ex,""); 117 | } 118 | } 119 | 120 | public void RegenerateStartupShortcut() 121 | { 122 | using (TaskService taskService = new TaskService()) 123 | { 124 | Task existingTask = taskService.FindTask(dataStorageFeature.Settings.AppName); 125 | if (existingTask != null) 126 | { 127 | CreateStartupShortcut(); 128 | } 129 | } 130 | } 131 | 132 | public void DeleteStartupShortcut() 133 | { 134 | using (TaskService taskService = new TaskService()) 135 | { 136 | Task existingTask = taskService.FindTask(dataStorageFeature.Settings.AppName); 137 | if (existingTask != null) 138 | { 139 | taskService.RootFolder.DeleteTask(dataStorageFeature.Settings.AppName); 140 | } 141 | } 142 | } 143 | 144 | public nint ReadForegroundWindow() 145 | { 146 | return GetForegroundWindow(); 147 | } 148 | 149 | public string GetProcessname(nint hWnd) 150 | { 151 | GetWindowThreadProcessId(hWnd, out uint processId); 152 | Process process = Process.GetProcessById((int)processId); 153 | 154 | const int nChars = 1024; 155 | StringBuilder applicationName = new StringBuilder(nChars); 156 | GetModuleFileNameEx(process.Handle, nint.Zero, applicationName, nChars); 157 | 158 | // Get only the executable file name 159 | string fileName = System.IO.Path.GetFileName(applicationName.ToString()); 160 | 161 | return fileName; 162 | } 163 | 164 | public List GetBackgroundApplicationsName() 165 | { 166 | HashSet Appnames = new(); 167 | 168 | List windows = new List(); 169 | 170 | bool EnumWindowsCallback(nint hWnd, nint lParam) 171 | { 172 | if (IsWindowVisible(hWnd)) 173 | { 174 | windows.Add(hWnd); 175 | } 176 | 177 | return true; 178 | } 179 | 180 | EnumWindows(EnumWindowsCallback, GCHandle.ToIntPtr(GCHandle.Alloc(windows))); 181 | 182 | foreach (nint windowId in windows) 183 | { 184 | Appnames.Add(GetProcessname(windowId)); 185 | } 186 | 187 | return Appnames.ToList(); 188 | } 189 | 190 | public Vector2 GetMousePos() 191 | { 192 | GetCursorPos(out POINT p); 193 | Vector2 pos = new Vector2(p.X, p.Y); 194 | 195 | return pos; 196 | } 197 | } 198 | } -------------------------------------------------------------------------------- /ViewModels/ViewDataPageVM.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using System; 4 | using System.Threading.Tasks; 5 | using WorkLifeBalance.Interfaces; 6 | using WorkLifeBalance.Models; 7 | using WorkLifeBalance.Services; 8 | using WorkLifeBalance.Services.Feature; 9 | 10 | namespace WorkLifeBalance.ViewModels 11 | { 12 | public partial class ViewDataPageVM : SecondWindowPageVMBase 13 | { 14 | [ObservableProperty] 15 | private TimeOnly recordMostWorked; 16 | [ObservableProperty] 17 | private DateOnly recordMostWorkedDate; 18 | 19 | [ObservableProperty] 20 | private TimeOnly recordMostRested; 21 | [ObservableProperty] 22 | private DateOnly recordMostRestedDate; 23 | 24 | [ObservableProperty] 25 | private float currentMonthWorkRestRatio = 0; 26 | [ObservableProperty] 27 | private int currentMonthTotalDays = 0; 28 | [ObservableProperty] 29 | private TimeOnly currentMonthMostWorked; 30 | [ObservableProperty] 31 | private TimeOnly currentMonthAverageWorked; 32 | [ObservableProperty] 33 | private DateOnly currentMonthMostWorkedDate; 34 | 35 | [ObservableProperty] 36 | private TimeOnly currentMonthMostRested; 37 | [ObservableProperty] 38 | private DateOnly currentMonthMostRestedDate; 39 | 40 | [ObservableProperty] 41 | private float previousMonthWorkRestRatio = 0; 42 | [ObservableProperty] 43 | private int previousMonthTotalDays = 0; 44 | [ObservableProperty] 45 | private TimeOnly previousMonthMostWorked; 46 | [ObservableProperty] 47 | private TimeOnly previousMonthAverageWorked; 48 | [ObservableProperty] 49 | private DateOnly previousMonthMostWorkedDate; 50 | 51 | [ObservableProperty] 52 | private TimeOnly previousMonthMostRested; 53 | [ObservableProperty] 54 | private DateOnly previousMonthMostRestedDate; 55 | 56 | private DataBaseHandler databaseHandler; 57 | private DataStorageFeature dataStorageFeature; 58 | private ISecondWindowService secondWindowService; 59 | public ViewDataPageVM(DataBaseHandler databaseHandler, DataStorageFeature dataStorageFeature, ISecondWindowService secondWindowService) 60 | { 61 | PageHeight = 580; 62 | PageWidth = 750; 63 | PageName = "View Data"; 64 | this.secondWindowService = secondWindowService; 65 | this.databaseHandler = databaseHandler; 66 | this.dataStorageFeature = dataStorageFeature; 67 | 68 | _ = CalculateData(); 69 | } 70 | 71 | public override async Task OnPageOppeningAsync(object? args = null) 72 | { 73 | await CalculateData(); 74 | } 75 | 76 | private async Task CalculateData() 77 | { 78 | DateOnly currentDate = dataStorageFeature.TodayData.DateC; 79 | DateOnly previousMonthDateTime = currentDate.AddMonths(-1); 80 | 81 | await CalculateCurrentMonth(currentDate); 82 | await CalculatePreviousMonth(previousMonthDateTime); 83 | await CalculateRecord(); 84 | CalculateWorkRatios(currentDate, previousMonthDateTime); 85 | } 86 | 87 | private async Task CalculateRecord() 88 | { 89 | DayData TempDay; 90 | 91 | TempDay = await databaseHandler.GetMaxValue("WorkedAmmount"); 92 | 93 | RecordMostWorked = TempDay.WorkedAmmountC; 94 | RecordMostWorkedDate = TempDay.DateC; 95 | 96 | TempDay = await databaseHandler.GetMaxValue("RestedAmmount"); 97 | 98 | RecordMostRested = TempDay.RestedAmmountC; 99 | RecordMostRestedDate = TempDay.DateC; 100 | } 101 | private async Task CalculateCurrentMonth(DateOnly currentDate) 102 | { 103 | try 104 | { 105 | 106 | DayData TempDay; 107 | 108 | int MonthToporkedSeconds = await databaseHandler.GetAvgSecondsTimeOnly("WorkedAmmount", currentDate.ToString("MM")); 109 | CurrentMonthAverageWorked = ConvertSecondsToTime(MonthToporkedSeconds); 110 | 111 | TempDay = await databaseHandler.GetMaxValue("WorkedAmmount", currentDate.ToString("MM"), currentDate.ToString("yyyy")); 112 | CurrentMonthMostWorked = TempDay.WorkedAmmountC; 113 | CurrentMonthMostWorkedDate = TempDay.DateC; 114 | 115 | TempDay = await databaseHandler.GetMaxValue("RestedAmmount", currentDate.ToString("MM"), currentDate.ToString("yyyy")); 116 | 117 | CurrentMonthMostRested = TempDay.RestedAmmountC; 118 | CurrentMonthMostRestedDate = TempDay.DateC; 119 | CurrentMonthTotalDays = await databaseHandler.ReadCountInMonth 120 | ( 121 | currentDate.ToString("MM"), 122 | currentDate.ToString("yyyy") 123 | ); 124 | } 125 | catch(Exception ex) 126 | { 127 | Console.WriteLine(ex); 128 | } 129 | } 130 | 131 | private async Task CalculatePreviousMonth(DateOnly previousDate) 132 | { 133 | DayData TempDay; 134 | 135 | int MonthToporkedSeconds = await databaseHandler.GetAvgSecondsTimeOnly("WorkedAmmount", previousDate.ToString("MM")); 136 | PreviousMonthAverageWorked = ConvertSecondsToTime(MonthToporkedSeconds); 137 | 138 | TempDay = await databaseHandler.GetMaxValue("WorkedAmmount", previousDate.ToString("MM"), previousDate.ToString("yyyy")); 139 | PreviousMonthMostWorked = TempDay.WorkedAmmountC; 140 | PreviousMonthMostWorkedDate = TempDay.DateC; 141 | 142 | TempDay = await databaseHandler.GetMaxValue("RestedAmmount", previousDate.ToString("MM"), previousDate.ToString("yyyy")); 143 | 144 | PreviousMonthMostRested = TempDay.RestedAmmountC; 145 | PreviousMonthMostRestedDate = TempDay.DateC; 146 | PreviousMonthTotalDays = await databaseHandler.ReadCountInMonth 147 | ( 148 | previousDate.ToString("MM"), 149 | previousDate.ToString("yyyy") 150 | ); 151 | } 152 | 153 | private void CalculateWorkRatios(DateOnly currentDate, DateOnly previousDate) 154 | { 155 | float MonthToporkedSeconds = ConvertTimeToSeconds(PreviousMonthAverageWorked); 156 | 157 | PreviousMonthWorkRestRatio = MonthToporkedSeconds == 0 ? 0 : MonthToporkedSeconds / 86400; 158 | PreviousMonthWorkRestRatio = (float)Math.Round(PreviousMonthWorkRestRatio, 2); 159 | 160 | MonthToporkedSeconds = ConvertTimeToSeconds(CurrentMonthAverageWorked); 161 | 162 | CurrentMonthWorkRestRatio = MonthToporkedSeconds == 0 ? 0 : MonthToporkedSeconds / 86400; 163 | CurrentMonthWorkRestRatio = (float)Math.Round(CurrentMonthWorkRestRatio, 2); 164 | } 165 | 166 | private TimeOnly ConvertSecondsToTime(int seconds) 167 | { 168 | int minutes = 0; 169 | int hours = 0; 170 | if (seconds != 0) 171 | { 172 | minutes = seconds / 60; 173 | seconds = seconds % 60; 174 | 175 | hours = minutes == 0 ? 0 : minutes / 60; 176 | minutes = minutes % 60; 177 | } 178 | return new TimeOnly(hours,minutes,seconds); 179 | } 180 | 181 | private int ConvertTimeToSeconds(TimeOnly time) 182 | { 183 | int seconds = 0; 184 | 185 | seconds += time.Second; 186 | seconds += time.Minute * 60; 187 | seconds += time.Hour * 60 * 60; 188 | 189 | return seconds; 190 | } 191 | 192 | [RelayCommand] 193 | private void SeePreviousMonth() 194 | { 195 | secondWindowService.OpenWindowWith(2); 196 | } 197 | 198 | [RelayCommand] 199 | private void SeeCurrentMonth() 200 | { 201 | secondWindowService.OpenWindowWith(1); 202 | } 203 | 204 | [RelayCommand] 205 | private void SeeAllDays() 206 | { 207 | secondWindowService.OpenWindowWith(0); 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /Views/BackgroundProcessesViewPage.xaml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 40 | 41 | 42 | 43 | 44 | 47 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 66 | 69 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 80 | 81 | 82 | 83 | 84 | 92 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 113 | 121 | 122 | 128 | 131 | 136 | 141 | 142 | 143 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /Services/DataBaseHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using WorkLifeBalance.Models; 4 | using System.Linq; 5 | 6 | namespace WorkLifeBalance.Services 7 | { 8 | public class DataBaseHandler 9 | { 10 | private readonly SqlDataAccess dataAccess; 11 | 12 | public DataBaseHandler(SqlDataAccess dataAccess) 13 | { 14 | this.dataAccess = dataAccess; 15 | } 16 | 17 | public async Task WriteAutoSateData(AutoStateChangeData autod) 18 | { 19 | autod.ConvertUsableDataToSaveData(); 20 | 21 | //I'm too dumb to figure out the sql for less calls 22 | string DeleteOldWorkingWindowsSQL = @"DELETE FROM WorkingWindows"; 23 | 24 | await dataAccess.ExecuteAsync(DeleteOldWorkingWindowsSQL, new { }); 25 | 26 | string InsertNewWorkingWindowsSQL = @"INSERT INTO WorkingWindows (WorkingStateWindows) 27 | VALUES (@WorkingWindow)"; 28 | 29 | foreach(string window in autod.WorkingStateWindows) 30 | { 31 | await dataAccess.WriteDataAsync(InsertNewWorkingWindowsSQL, new { WorkingWindow = window }); 32 | } 33 | 34 | string UpdateActivitySql = @"UPDATE Activity 35 | SET TimeSpent = @TimeSpent 36 | WHERE Date = @Date AND Process = @Process"; 37 | 38 | string InsertActivitySql = @"INSERT INTO Activity (Date,Process,TimeSpent) 39 | VALUES (@Date,@Process,@TimeSpent)"; 40 | 41 | foreach (ProcessActivityData activity in autod.Activities) 42 | { 43 | int affectedRows = await dataAccess.WriteDataAsync(UpdateActivitySql, activity); 44 | 45 | if (affectedRows == 0) 46 | { 47 | await dataAccess.WriteDataAsync(InsertActivitySql, activity); 48 | } 49 | } 50 | 51 | } 52 | 53 | public async Task ReadAutoStateData(string date) 54 | { 55 | AutoStateChangeData retrivedSettings = new(); 56 | 57 | string sql = @$"SELECT * FROM Activity 58 | WHERE Date = @Date"; 59 | 60 | retrivedSettings.Activities = (await dataAccess.ReadDataAsync(sql, new { Date = date })).ToArray(); 61 | 62 | sql = @$"SELECT * FROM WorkingWindows"; 63 | 64 | retrivedSettings.WorkingStateWindows = (await dataAccess.ReadDataAsync(sql, new { })).ToArray(); 65 | 66 | retrivedSettings.ConvertSaveDataToUsableData(); 67 | 68 | return retrivedSettings; 69 | } 70 | 71 | public async Task> ReadDayActivity(string date) 72 | { 73 | List ReturnActivity = new(); 74 | 75 | string sql = @$"SELECT * from Activity 76 | WHERE Date Like @Date"; 77 | 78 | 79 | ReturnActivity = (await dataAccess.ReadDataAsync(sql, new { Date = date })).ToList(); 80 | 81 | foreach (ProcessActivityData day in ReturnActivity) 82 | { 83 | day.ConvertSaveDataToUsableData(); 84 | } 85 | 86 | return ReturnActivity; 87 | } 88 | 89 | public async Task WriteSettings(AppSettingsData sett) 90 | { 91 | sett.ConvertUsableDataToSaveData(); 92 | 93 | string sql = @"UPDATE Settings 94 | SET LastTimeOpened = @LastTimeOpened, 95 | StartWithWindows = @StartWithWindows, 96 | SaveInterval = @SaveInterval, 97 | AutoDetectInterval = @AutoDetectInterval, 98 | AutoDetectIdleInterval = @AutoDetectIdleInterval, 99 | MinimizeToTray = @MinimizeToTray 100 | LIMIT 1"; 101 | 102 | await dataAccess.WriteDataAsync(sql, sett); 103 | } 104 | 105 | public async Task ReadSettings() 106 | { 107 | AppSettingsData? retrivedSettings; 108 | 109 | string sql = @$"SELECT * FROM Settings 110 | LIMIT 1"; 111 | 112 | retrivedSettings = (await dataAccess.ReadDataAsync(sql, new { })).FirstOrDefault(); 113 | 114 | retrivedSettings ??= new(); 115 | 116 | retrivedSettings.ConvertSaveDataToUsableData(); 117 | 118 | return retrivedSettings; 119 | } 120 | 121 | public async Task WriteDay(DayData day) 122 | { 123 | day.ConvertUsableDataToSaveData(); 124 | 125 | string sql = @"INSERT OR REPLACE INTO Days (Date,WorkedAmmount,RestedAmmount,IdleAmmount) 126 | VALUES (@Date,@WorkedAmmount,@RestedAmmount,@IdleAmmount)"; 127 | 128 | await dataAccess.WriteDataAsync(sql, day); 129 | } 130 | 131 | public async Task ReadDay(string date) 132 | { 133 | DayData? retrivedDay; 134 | 135 | string sql = @$"SELECT * FROM Days 136 | WHERE Date = @Date"; 137 | retrivedDay = (await dataAccess.ReadDataAsync(sql, new { Date = date })).FirstOrDefault(); 138 | 139 | retrivedDay ??= new(); 140 | 141 | retrivedDay.ConvertSaveDataToUsableData(); 142 | 143 | return retrivedDay; 144 | } 145 | 146 | public async Task ReadCountInMonth(string month, string year) 147 | { 148 | int affectedRows = 0; 149 | string sql = @$"SELECT COUNT(*) AS row_count 150 | FROM Days WHERE date LIKE @Pattern"; 151 | affectedRows = await dataAccess.ExecuteAsync(sql, new { Pattern = $"{month}%{year}" }); 152 | 153 | return affectedRows; 154 | } 155 | 156 | public async Task> ReadMonth(string Month = "", string year = "") 157 | { 158 | List ReturnDays = new(); 159 | 160 | string sql; 161 | if (string.IsNullOrEmpty(Month) || string.IsNullOrWhiteSpace(year)) 162 | { 163 | sql = @$"SELECT * from Days"; 164 | } 165 | else 166 | { 167 | sql = @$"SELECT * from Days 168 | WHERE Date Like @Pattern"; 169 | } 170 | 171 | ReturnDays = (await dataAccess.ReadDataAsync(sql, new { Pattern = $"{Month}%{year}" })).ToList(); 172 | 173 | foreach (DayData day in ReturnDays) 174 | { 175 | day.ConvertSaveDataToUsableData(); 176 | } 177 | 178 | return ReturnDays; 179 | } 180 | 181 | public async Task GetMaxValue(string collumnData, string Month = "", string year = "") 182 | { 183 | DayData? retrivedDay = null; 184 | 185 | string sql; 186 | 187 | if (string.IsNullOrEmpty(Month) || string.IsNullOrEmpty(year)) 188 | { 189 | //pass the value directly because it brokes if I use it as a parameter 190 | sql = @$"SELECT * FROM Days 191 | WHERE CAST({collumnData} as INT) = 192 | (SELECT MAX(CAST({collumnData} as INT)) FROM Days)"; 193 | retrivedDay = (await dataAccess.ReadDataAsync(sql, new { })).FirstOrDefault(); 194 | } 195 | else 196 | { 197 | sql = @$"SELECT * FROM Days 198 | WHERE CAST({collumnData} as INT) = 199 | (SELECT MAX(CAST({collumnData} as INT)) FROM Days 200 | WHERE Date LIKE @Template)"; 201 | 202 | 203 | retrivedDay = (await dataAccess.ReadDataAsync(sql, new { Template = $"{Month}%{year}" })).FirstOrDefault(); 204 | } 205 | 206 | retrivedDay ??= new(); 207 | 208 | retrivedDay.ConvertSaveDataToUsableData(); 209 | 210 | return retrivedDay; 211 | } 212 | 213 | public async Task GetAvgSecondsTimeOnly(string timeOnlyCollumn, string Month = "", string year = "") 214 | { 215 | int avgAmount; 216 | 217 | string sql = @$"WITH ConvertedTimes AS 218 | ( 219 | SELECT 220 | (CAST(SUBSTR({timeOnlyCollumn}, 1, 2) AS INTEGER) * 3600 + 221 | CAST(SUBSTR({timeOnlyCollumn}, 3, 2) AS INTEGER) * 60 + 222 | CAST(SUBSTR({timeOnlyCollumn}, 5, 2) AS INTEGER)) AS TotalSeconds, date FROM Days 223 | ) 224 | SELECT COALESCE(AVG(TotalSeconds), 0) AS AvgSeconds 225 | FROM ConvertedTimes WHERE date LIKE @Template"; 226 | 227 | avgAmount = (await dataAccess.ReadDataAsync(sql, new { Template = $"{Month}%{year}" })).FirstOrDefault(); 228 | 229 | return avgAmount; 230 | } 231 | 232 | public async Task GetMostActiveActivity(string activity, string Month = "", string year = "") 233 | { 234 | ProcessActivityData? retrivedDay = null; 235 | 236 | string sql; 237 | if (string.IsNullOrEmpty(Month) || string.IsNullOrEmpty(year)) 238 | { 239 | sql = @$"SELECT * FROM Days 240 | WHERE @Activity = 241 | (SELECT MAX(@Activity) FROM Days)"; 242 | } 243 | else 244 | { 245 | 246 | sql = @$"SELECT * FROM Days 247 | WHERE @Activity = 248 | (SELECT MAX(@Activity) FROM Days 249 | WHERE Date Like @Pattern)"; 250 | } 251 | retrivedDay = (await dataAccess.ReadDataAsync(sql, new { Activity = activity, Pattern = $"{Month}%{year}" })).FirstOrDefault(); 252 | 253 | retrivedDay ??= new(); 254 | 255 | retrivedDay.ConvertSaveDataToUsableData(); 256 | 257 | return retrivedDay; 258 | } 259 | 260 | } 261 | } --------------------------------------------------------------------------------